Vue组件间通信:表单提交成功后从子组件触发TabIndex切换至初始标签页
Let's walk through a straightforward solution using Vue's custom event system to make the parent component switch tabs once the child's form submits successfully.
Step 1: Emit a Custom Event from the Child Component
In your BatchMain child component's onSubmit function, right after showing the success toast, add a line to emit an event that the parent can listen for. We'll name this event switch-to-first-tab:
async onSubmit(evt) { evt.preventDefault(); if (!this.validateForm()) return; try { let data = { name: this.form.name, description: this.form.description, shellfish: this.form.shellfish, stockType: this.form.stockType, gradeList: this.form.gradeList, age: this.form.age, quantity: this.form.quantity, source: this.form.source, hatchery: this.form.hatchery, location: this.form.location, }; let response = await batchService.addBatch(data); if (response.status === 200) { makeToast.call( this, "Success", "Batch is created successfully", "success" ); // Notify parent to switch back to the first tab this.$emit('switch-to-first-tab'); setTimeout(() => { this.$router.replace({ name: "StockMain" }); }, 1000); } } catch (e) { console.log("e", e); makeToast.call(this, "Error", "Error creating batch", "danger"); } }
Step 2: Listen for the Event in the Parent Component
Next, update the parent component to catch this event and set tabIndex back to 0.
First, modify the BatchMain tag in the parent's template to attach the event listener:
<b-tab title="Batches"> <BatchMain @switch-to-first-tab="switchToFirstTab"></BatchMain> </b-tab>
Then, add a method in the parent's methods section to handle the tab switch:
export default { components: { PieChart, BatchMain }, data() { return { backgroundColor: [], chartData: {}, measurement: "", farmStock: 0, gradeStock: [], isData: false, batches: [], fields: ["name", "age", "quantity", "shellfish", "stock_type"], tabIndex: 0, }; }, methods: { switchToFirstTab() { this.tabIndex = 0; } } }
How This Works
- Vue's
$emitlets child components send custom events up to their parents. The parent listens for this event using the@event-namesyntax. - Since your
b-tabsusesv-model="tabIndex"for two-way binding, settingtabIndexto 0 will instantly switch the active tab back to the first one.
Edge Case Note
If your $router.replace call reloads the parent component, tabIndex will automatically reset to 0 (since it's initialized to 0 in data). But if the route navigation keeps the same parent component instance (common in SPAs), the event-based approach ensures the tab switches immediately after submission, even before the redirect.
内容的提问来源于stack exchange,提问作者Michal Kubiak

