Vue实现标签页激活时加载表格数据,而非创建时加载
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.tabEvent: 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-tablecomponent using:ref="table-${index}". This lets us directly access the component instance and call itsloadmethod. - Initial Load: The
mountedhook triggers the load for the first tab since it's active by default.
Notes
- Ensure your
my-tablecomponent exposes theloadmethod in itsmethodsobject (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

