How to navigate to specific tab in Bootstrap-vue tabs in vue routes?

Viewed 10503

I am using Bootstrap-vue tabs. This is HTML for tabs:

<b-tabs>
  <b-tab title="Exotic Dogs" href="#dogs">
    <br>Dogs here
  </b-tab>
  <b-tab title="Exotic Cats"  href="#cats">
    <br>Cats here
  </b-tab>

</b-tabs>

Here is the route for cats:

{
        path: '/animals/:id#cats',
        name: 'getCats',
        component: Animals // removed from HTML to simplify
    },

In component code:

this.$router.replace({ name: 'getCats', params: { id: this.$route.params.id }})

This will take to:

localhost:3000/animals/234909888#cats

But dogs tab is open (the first tab) instead of cats tab. Also refreshing browser will display blank page.

How to fix this issue?

1 Answers

You could try adding v-model="tabIndex" to the <b-tabs> tag, and use $route.hash to set it in mounted().

<b-tabs v-model="tabIndex">
  <b-tab title="Exotic Dogs" href="#dogs">
    <br>Dogs here
  </b-tab>
  <b-tab title="Exotic Cats"  href="#cats">
    <br>Cats here
  </b-tab>

</b-tabs>
export default {
  ...
  data() {
    return {
      tabIndex: 0,
      tabs: ['#dogs', '#cats']
    }
  },
  mounted() {
    this.tabIndex = this.tabs.findIndex(tab => tab === this.$route.hash)
  }
  ...
}
Related