最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I toggle a class to show which tab is active in VueJS? - Stack Overflow

programmeradmin0浏览0评论

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

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']
        };
    },
})
Share Improve this question asked Apr 22, 2019 at 11:57 Al-76Al-76 1,8786 gold badges26 silver badges46 bronze badges 1
  • You can use the .exact-active-class class in your styles, no need to do anything in your JS or JSX – Alicia Sykes Commented Apr 22, 2019 at 12:05
Add a comment  | 

2 Answers 2

Reset to default 12

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

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

发布评论

评论列表(0)

  1. 暂无评论