【问题标题】:How do I toggle a class to show which tab is active in VueJS?如何切换一个类以显示 VueJS 中哪个选项卡处于活动状态?
【发布时间】:2019-09-11 15:00:48
【问题描述】:

我创建了两个选项卡,默认情况下我希望第一个<li> 上的活动集类。

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

我可以使用 CSS 来创建一些样式规则,以便直观地指示哪个选项卡当前处于活动状态。

我还创建了一个JS Fiddle 来查看当前输出。

欢迎任何帮助,因为我有点卡住了。

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

【问题讨论】:

  • 您可以在您的样式中使用.exact-active-class 类,无需在您的 JS 或 JSX 中做任何事情

标签: javascript vue.js vuejs2 v-for


【解决方案1】:

使用这个 -

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

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

让我知道它是否有效。

小提琴 - https://jsfiddle.net/so3mf8h9/


更新

你也可以使用三元运算符,它应该也可以。

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

【讨论】:

    【解决方案2】:

    编辑啊,抱歉,我以为你在使用 vue-router。当您的网站变得更大时,开始使用路由器可能是一个想法,当您这样做时,此方法将适用于您 ?


    Vue 内置了这个功能?

    您需要做的就是将其添加到您的样式表中

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

    参考:Vue documentation

    这是我如何在几周前创建的 Vue 站点中实现它的示例:MarkupStyles。希望对您有所帮助,如果您对实现此功能还有任何疑问,请告诉我?

    【讨论】:

    • 感谢艾丽西亚的帮助。很受好评。不知道如何让你的方法适用于我的标签,因为我没有在这里使用路由。
    • 是的,我很抱歉没有正确阅读问题;)我已经更新了我的答案
    • 好的。伟大的。对于这个问题,我将使用@Siddharths 方法,但感谢您现在对路由的注意。你真好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 2012-08-09
    • 2011-05-17
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多