user10622347
user10622347

Reputation:

How to store state of tabs based on route?

Is it possible to store different state of a <v-tab> component based on the route i'm currently on? What i'm basically trying to achieve is, have a single component like the code below that i use in several different routes, but have it remember the tab i'm currently at depending on the route.

  <v-layout justify-space-around row>
    <v-tab v-for="tab in navbarTabs" :key="tab.id">{{ tab.name }}</v-tab>
  </v-layout>

data() {
 return {
    navbarTabs: [
    {
      id: 0,
      name: "Home"
    },
    {
      id: 1,
      name: "Schedule"
    },
    {
      id: 2,
      name: "Tech card"
    },
    {
      id: 3,
      name: "Specifications"
    },
    {
      id: 4,
      name: "Control card"
    },
    {
      id: 5,
      name: "Packing"
    }
  ]
 }
}

I previously managed to achieve the desired result by having a few identical <v-tab> components that i visualised conditionally based on current route with v-if, but that solutions seems a bit crude and not scalable at all. Can someone give me some pointers on how to achieve that? Thanks in advance!

Upvotes: 2

Views: 2472

Answers (1)

D Malan
D Malan

Reputation: 11434

The v-tabs component has a value prop which you can use to open a tab with a given key. And the v-tab component has a to prop which you can use to set the route of a tab. So essentially, you can use Vue Router params to select a tab and you can set the route using the v-tab's to prop.

You can define your route like this to pass the selectedTab param to the component:

 routes: [
    { path: '/tabs/:selectedTab', component: TabsComponent, props: true },
 ]

And your TabsComponent can look something like this:

<template>
  <v-layout justify-space-around row>
     <v-tabs v-model="selectedTab">
       <v-tab 
         v-for="tab in navbarTabs"
         :key="tab.id"
         :to=`/tabs/${tab.id}`
       >{{ tab.name }}</v-tab>
     </v-layout>
</template>

<script>
  export default {
    props: ['selectedTab'],
  }
</script>

Upvotes: 4

Related Questions