When using Vuetify tabs, how do I remove a tab AND any components within that tab?
For example
- I dynamically add three tabs and each has a nested text area component
- I add some text in each tab’s text area (“tab 0” for tab 0, “tab 1” for tab 1, etc).
- If I remove the tab at index 1, the text area that was displaying “tab 1” now shows up under tab 2
After removing Tab 1, Tab 2 displays Tab 1’s text:
I can see that the text area component is just staying associated with the tab that is at index 1, but I can’t figure out how to change this to act as I would expect. How can I remove both the nested text area component and the tab so the remaining ones stay together?
Here’s the data & methods I’m using
data: () => ({ selectedTab: "tab-0", tabCount: 0, tabs: [{ title: "Tab 0" }] }), methods: { addTab() { this.tabCount++; let newTabIndex = this.tabs.length; let title = "Tab " + this.tabCount; this.tabs.push({ title: title }); this.$nextTick(() => { this.selectedTab = "tab-" + newTabIndex; }); }, removeTab(index) { this.tabs.splice(index, 1); if (!this.tabs.length) this.addTab(); }, },
And the template:
<template> <div class="ma-5"> <v-tabs centered dense v-model="selectedTab" show-arrows> <v-tab v-for="(t, index) in tabs" :key="index" :href="'#tab-' + index"> {{ t.title }} <v-btn icon @click="removeTab(index)" class="ml-2" ><v-icon x-small>mdi-close</v-icon></v-btn > </v-tab> </v-tabs> <v-tabs-items v-model="selectedTab" class="pt-2"> <v-tab-item transition="fade-transition" reverse-transition="fade-transition" v-for="(t, index) in tabs" :key="index" :value="'tab-' + index" > <v-textarea outlined class="mx-auto"></v-textarea> </v-tab-item> </v-tabs-items> </div> </template>
Answer
That is because you are using “index” as key for the tabs:
<v-tab v-for="(t, index) in tabs" :key="index" :href="'#tab-' + index">
You need to use something more unique. I’d suggest, in your example, to use the tab’s title:
<v-tab v-for="(t, index) in tabs" :key="t.title" :href="'#tab-' + index">
You need to change also the line that creates the actual content:
<v-tab-item transition="fade-transition" reverse-transition="fade-transition" v-for="(t, index) in tabs" :key="t.title" :value="'tab-' + index" >