Al-76
Al-76

Reputation: 1868

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']
        };
    },
})

Upvotes: 7

Views: 18944

Answers (2)

arora
arora

Reputation: 869

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' : ''"

Upvotes: 12

Alicia Sykes
Alicia Sykes

Reputation: 7067

Edit: Ah, sorry I thought you were using vue-router. When your site gets bigger, it may be an idea to start using router, and when you do, this method will work for you 🤓


Vue has this functionality built in 🙌

All you need to do is add this into your stylesheet

.router-link-exact-active {
    // Your styles go here
    border: 5px dashed red;
}

Reference: Vue documentation

Here's an example of how I implemented it in a Vue site I made a couple weeks back: Markup, and Styles. Hope that helps, let me know if you've got any more questions on implementing this 😊

Upvotes: 2

Related Questions