Search code examples
vue.jsbootstrap-vue

Show different component conditionally if parent tag contains active class - Vue Bootstrap


I want to customize tab component's title part on Vue Bootstrap. If the tab is active, I want to show different type of tab item. Of course we can solve it by using css classes by setting .active class. But In my situation, I want to display a different component if that tab is active.

I believe this can be done using 'v-if' but I dont know how to get its tag's classes contains active class. If tab is active, I want to render a spinner component, else I only want to render name of that tab.

Do you have any idea?

<b-tabs fill>  
        <b-tab title="First">
            <template #title v-if="active">
                <b-spinner type="grow" small variant="success"></b-spinner> <b>Active Title</b>
            </template>
            <template #title v-else> 
                <b>Title</b>
            </template>
        </b-tab>
        <b-tab title="Second">
            <template #title v-if="active"> 
                <b-spinner type="grow" small variant="success"></b-spinner> <b>Second Title</b>
            </template>
            <template #title v-else> 
                <b>Title</b>
            </template>
        </b-tab>

Solution

  • You could bind a property to <b-tabs> v-model, which will contain the index of the active tab. Then use this to check inside your v-if whether the tab is active or not.

    new Vue({
      el: '#app',
      data() {
        return {
          currentTab: 0
        }
      }
    });
    <link href="https://unpkg.com/bootstrap@4.5.3/dist/css/bootstrap.min.css" rel="stylesheet" />
    
    <script src="https://unpkg.com/vue@2.6.12/dist/vue.js"></script>
    <script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script>
    
    <div id="app" class="p-4">
      <b-tabs v-model="currentTab" fill>
        <b-tab title="First">
          <template #title v-if="currentTab === 0">
            <b-spinner type="grow" small variant="success"></b-spinner> <b>Active Title</b>
          </template> Tab 1 content
        </b-tab>
        <b-tab title="Second">
          <template #title v-if="currentTab === 1"> 
            <b-spinner type="grow" small variant="success"></b-spinner> <b>Second Title</b>
          </template> Tab 2 content
        </b-tab>
      </b-tabs>
    </div>