Vuetify: How to preselect active tab?
Use v-model
:
<v-tabs v-model="activetab_href_variable">
There is no info about it (on 05/17/2018) in current version docs but 0.17 (https://vuetifyjs.com/releases/0.17/#/components/tabs) have that:
v-model String - Current selected tab
To preselect an active tab:
<v-tabs grow v-model="active_tab">
<v-tab v-for="tab of tabs" :key="tab.id">
{{tab.name}}
</v-tab>
</v-tabs>
The script part:
export default {
data: () => ({
active_tab: 2,
tabs: [
{ id: 1, name: 'tab1' },
{ id: 2, name: 'tab2' },
{ id: 3, name: 'tab3' }
]
})
}
See it in action here
Note: We have preselect the tab with name tab3.
Keep in mind that vuetify will set the
active_tab
to the index of the active tab. So the index of the item with id 3 is 2 because it's starting from 0.
For this example I used vuetify version: 1.1.9
To achieve that you could store the current tab in the URL, either as a nested route or as a query parameter.
I end up using the latter solution quite often, to avoid creating a separate child component for each tab content. Here's how it works:
- First useful step (but not 100% obligatory), is to name the tabs, so we can refer to them by name rather than ordinal number. This can be achieved by specifying
href
andvalue
props as follows:
<v-tabs v-model="tab">
<v-tab href="#one">
One
</v-tab>
<v-tab-item value="one">
Tab content
</v-tab-item>
</v-tabs>
- Next we can store the current tab as query parameter using a computed property with a setter:
computed: {
tab: {
set (tab) {
this.$router.replace({ query: { ...this.$route.query, tab } })
},
get () {
return this.$route.query.tab
}
}
}
- Now you can open a specific tab by following a link such as
/page?tab=one
(works for buttons, router links, to share a tab link with someone, etc.)
This solution applies to Vuetify.js 2.x. I wrote a short article with complete code example explaining it in detail: https://medium.com/@jareklipski/linking-to-a-specific-tab-in-vuetify-js-d978525f2e1a