You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue实现标签页激活时加载表格数据,而非创建时加载

Solution to Load Tab Content Only When Clicked

First, let's fix a small but critical issue in your tab pane IDs: the href in your tab links uses #tab-3${index}, so the corresponding pane's id should be tab-3${index} (without the leading #). That's necessary for Bootstrap's tab functionality to work correctly.

To load your my-table data only when a tab is activated, we can leverage Bootstrap's native tab events and Vue's ref system to trigger the load method on demand. Here's how to implement it:

Step 1: Update the Template

Modify your tab structure to include event listeners and refs for your table components:

<ul class='nav nav-tabs'>
  <li v-for='(item, index) in userfilterresults' :key="index">
    <a 
      data-toggle='tab' 
      :href="`#tab-3${index}`" 
      @shown.bs.tab.native="() => handleTabShown(index)"
    >{{ item.name }}</a>
  </li>
</ul>
<div class='tab-content'>
  <div 
    :id="`tab-3${index}`" 
    class='tab-pane' 
    v-for='(item, index) in userfilterresults' 
    :key="index"
    :class="{ active: index === 0 }" <!-- Set first tab as active by default -->
  >
    <my-table 
      :url='`tasks/getall`' 
      :ref="`table-${index}`"
    ></my-table>
  </div>
</div>

Step 2: Add the Event Handler and Initial Load

In your component's script, add a method to handle the tab shown event, and load data for the initially active tab on mount:

export default {
  data() {
    return {
      userfilterresults: [] // Your tab data here
    };
  },
  mounted() {
    // Load data for the first (initially active) tab
    this.handleTabShown(0);
  },
  methods: {
    handleTabShown(index) {
      // Get the reference to the corresponding table component
      const tableInstance = this.$refs[`table-${index}`][0];
      // Trigger the load method on the table
      tableInstance.load();
    }
  }
};

How This Works

  • Bootstrap's shown.bs.tab Event: This event fires after a tab has been fully activated (and its pane is visible). We listen to this native DOM event using @shown.bs.tab.native.
  • Vue Refs: We assign a unique ref to each my-table component using :ref="table-${index}". This lets us directly access the component instance and call its load method.
  • Initial Load: The mounted hook triggers the load for the first tab since it's active by default.

Notes

  • Ensure your my-table component exposes the load method in its methods object (so it's accessible via $refs).
  • If you're using Vue 3, the ref syntax is slightly different (you'd use ref() with an array), but the core logic remains the same.

内容的提问来源于stack exchange,提问作者Robert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:17:49