Search code examples
javascriptvue.jsvuejs2v-for

How do I toggle a class to show which tab is active in VueJS?


I have created two tabs, which I would like the class of active set on the first <li> by default.

Then, when the second tab is selected, the .active class should pass to the second <li> and be removed from the first.

I can use CSS to create some style rules in order to give a visual indicator as to which tab is currently active.

I have also created a JS Fiddle to see the current output.

Any help welcome as I am rather stuck.

<ul class="overlay-panel-actions-primary">
    <li v-for="(tab, index) in tabs" @click="currentTab = index">{{tab}}</li>
</ul>
<div class="content-bd">
    <div class="tab-content">
        <div v-show="currentTab === 0">
            List of filters options
        </div>
        <div v-show="currentTab === 1">
            List of sort options
        </div>
    </div>
</div>

new Vue({
  el: "#app",
    data() {
        return {
            currentTab: 0,
            tabs: ['Filter', 'Sort']
        };
    },
})

Solution

  • Use this -

    :class="{active: currentTab === index}"

    <li v-for="(tab, index) in tabs" @click="currentTab = index" :class="{active: currentTab === index}">{{tab}}</li>
    

    Let me know if it works.

    Fiddle - https://jsfiddle.net/so3mf8h9/


    Update

    You can also use ternary operator, It should also work.

    :class="currentTab === index ? 'active' : ''"