Home > Net >  Vue how to set the active tab
Vue how to set the active tab

Time:06-09

I have a Vue tab component that console logs out the correct index of the selected tab but I don't know how to set the active tab so it is opened. Any help or direction would be appreciated.

Component:

<Tabs
  :tabs="tabs"
  :active-tab-index="activeTab"
  @tab-changed="changeTab"
/>

Markup

<div v-show="activeTab === 0">
Show tab one content
</div>

<div v-show="activeTab === 1">
Show tab two content
</div>

Data:

  data() {
    return {
      tabs: [
        { id: 0, name: 'Tab One' },
        { id: 1, name: 'Tab Two' },
      ],
      activeTab: 0,
    }
  },

Method:

changeTab(index) {
  console.log('Change activeTab', index)
},

CodePudding user response:

it's not completely clear to me where the method and data is, but I assume it's in the parent, so in that case you'd simply need to change the function to something like this:

changeTab(index) {
  this.activeTab = index
},

your component could be even cleaner if it would provide option to use v-model on it like: v-model:activeTabIndex="activeTab". To make this happen you'd just need to emit the data inside the component with update:activeTabIndex instead of tab-changed.

  • Related