Vuetify: How to preselect active tab?

試著忘記壹切 提交于 2019-12-21 04:22:09

问题


I want to use Vuetify (v1.0.18) to render some static navigation using v-tabs. The routing is done on the server side, so I need a way to set the active tab by properties. It's a very basic task, but I don't get it to work. Example:

<v-tabs>
  <v-tab href="/path1">Tab 1</v-tab>
  <v-tab href="/path2">Tab 2</v-tab>
</v-tabs>

This preselects the first tab - fine.

Now the question ist: How to preselect the second tab? The following does not work:

<v-tabs value="tab2">
  <v-tab id="tab1" href="/path1">Tab 1</v-tab>
  <v-tab id="tab2" href="/path2">Tab 2</v-tab>
</v-tabs>

回答1:


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




回答2:


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




回答3:


Set the v-model inside the mounted() callback of the component hosting the v-tabs

<v-tabs v-model="selectedTab">
  <v-tab key='first'>First</v-tab>
  <v-tab key='second'>Second</v-tab>
</v-tabs>



<script>
export default {
   ...
   mounted() {
     this.selectedTab = 'first';
   },
   ...
}
</script>



回答4:


As a workaround I made a wrapper component:

<template>
  <v-tabs v-model="selectedTab">
    <slot></slot>
  </v-tabs>
</template>

<script>
  export default {
    name: 'StaticTabs',

    props: [ 'selected' ],

    mounted() {
      this.selectedTab = this.selected
    },

    data: () => ({
      selectedTab: null
    }),
  }
</script>

Use it with this:

<static-tabs selected="/path2">
  <v-tab id="tab1" href="/path1">Tab 1</v-tab>
  <v-tab id="tab2" href="/path2">Tab 2</v-tab>
</static-tabs>

Lots of code for a very basic task, but it works.




回答5:


I solved this with this.$refs

<v-tab v-model="tab1" ref="tab1">

Text for tab1 Text for tab2 Text for tab3

// Inside a method
someButton() {
  this.$refs.tab2.click()
}


来源:https://stackoverflow.com/questions/50392918/vuetify-how-to-preselect-active-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!