How to use Vuetify tabs with vue-router
I'm just adding some animation-related tips here & clarifying the use of v-tab-items
vs v-tab-item
.
If you have noticed, using the working markup as follows prevents the v-tabs tab switch animation to work:
<v-tabs v-model="activeTab">
<v-tab key="tab-1" to="/tab-url-1">tab 1</v-tab>
<v-tab key="tab-2" to="/tab-url-2">tab 2</v-tab>
</v-tabs>
<router-view />
If you want to keep the tab switch animation, this is a way to do it.
<v-tabs v-model="activeTab">
<v-tab key="tab-1" to="/tab-url-1" ripple>
tab 1
</v-tab>
<v-tab key="tab-2" to="/tab-url-2" ripple>
tab 2
</v-tab>
<v-tab-item id="/tab-url-1">
<router-view v-if="activeTab === '/tab-url-1'" />
</v-tab-item>
<v-tab-item id="/tab-url-2">
<router-view v-if="activeTab === '/tab-url-2'" />
</v-tab-item>
</v-tabs>
Note that you can also use a
v-for
loop on yourv-tab
andv-tab-item
tags as long as yourto
value is found among theid
attribute of yourv-tab-item
s.If you need to place your tab contents in a different place than your tabs buttons, this is what
v-tab-items
is for. You can place thev-tab-item
s in av-tab-items
tag outside of thev-tabs
component. Make sure you give it av-model="activeTab"
attribute.
The template part:
<div>
<v-tabs
class="tabs"
centered
grow
height="60px"
v-model="activeTab"
>
<v-tab v-for="tab in tabs" :key="tab.id" :to="tab.route" exact>
{{ tab.name }}
</v-tab>
</v-tabs>
<router-view></router-view>
</div>
And the js part:
data() {
return {
activeTab: `/user/${this.id}`,
tabs: [
{ id: 1, name: "Task", route: `/user/${this.id}` },
{ id: 2, name: "Project", route: `/user/${this.id}/project` }
]
};
}
Routes:
{
path: "/user/:id",
component: User1,
props: true,
children: [
{
path: "", //selected tab by default
component: TaskTab
},
{
path: "project",
component: ProjectTab
}
]
}
See codesanbox example
Update
Holy wow! I asked the Vuetify community to add documentation to their api, and it looks like they just added the to
prop as well as other vue-router
props to the Vuetify tabs docs. Seriously, the community there is awesome.
Original Answer
The folks in the Vuetify community Discord were able to help me out. My updated jsfiddle now has the working code.
Essentially, v-tab
is a wrapper for router-link
, where I assume it uses slots to pass props to router-link
, so putting the to
prop on v-tab
works fine.
The following code is an example of the working code:
html
<v-app dark>
<v-tabs fixed-tabs>
<v-tab to="/foo">Foo</v-tab>
<v-tab to="/bar">Bar</v-tab>
</v-tabs>
<router-view></router-view>
</v-app>
js
const Foo = {
template: '<div>Foo component!</div>'
};
const Bar = {
template: '<div>Bar component!</div>'
};
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar },
];
const router = new VueRouter({ routes });
new Vue({
el: '#app',
router,
});
Result