VueJs 设置活动类,当一个 li 元素在 v-for 循环中单击时 [英] VueJs set active class, when one li element clicked in v-for loop

查看:45
本文介绍了VueJs 设置活动类,当一个 li 元素在 v-for 循环中单击时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我执行 v-for 循环并且已经选择了一个类时,我无法弄清楚如何正确选择(设置活动类).让我分享代码并进一步解释

I can't figure out how to properly select (set active class) when I do v-for loop and one class is already selected. Let me share the code and with further explanation

这些是我的可用订阅,并且已经根据用户数据选择了其中一个

These are my available subscriptions and one is already selected, based on user data

<ul>
    <li v-for="(s, key, index) in subscriptions"
        :class="checkIfClassActive(s.subscription_key)"
        @click="setActive(key, index)">
        {{ s.name }}
    </li>
</ul>

和我的js代码

checkIfClassActive(userSubscriptionKey) {
    if (userSubscriptionKey === this.userSubscription.subscription_key) {
        return 'active';
    }
},
setActive(key, index) {

},

这就是显示的方式

现在下一步是当我单击一个 li 元素时,它应该变为活动状态,所有其他 li 元素都应该失去活动类,但问题是我不知道如何正确编写 setActive 函数.你能帮我吗,怎么做.

Now the next step is when I click on one li element it should become active and all other li elements should lose active class, but the problem is that I can't figure out how to properly write setActive function. Can you please help me out, how to do this.

如果您需要任何其他信息,请告诉我,我会提供.谢谢!

If you need any additional informations, let me know and I will provide. Thank you!

推荐答案

添加一个名为 activeIndexdata 属性:

Add a data property called activeIndex:

  data() {
    return {
      activeIndex: undefined
    }
  },

和你的 setActive 方法:

  methods: {
    setActive(subscription, index) { 
      this.activeIndex = index;
      this.userSubscription.subscription_key = subscription.subscription_key
},
    getSubscriptions() {
       .....
       // fetch subscriptions in this.subscriptions var
       .....
       // select preselected subscription, when fetching subscriptions 
       let userSubscriptionKey = this.userSubscription.subscription_key;
       let indexOfObject = this.subscriptions.findIndex(
            o => o.subscription_key === userSubscriptionKey
       );
       this.setActive(this.userSubscription, indexOfObject);

    }
  }

对您的模板稍作修改:

<ul>
    <li v-for="(s, index) in subscriptions"
        :class="{ 'active': activeIndex === index }" :key="s.id"
        @click="setActive(s, index)">
        {{ s.name }}
    </li>
</ul>

您基本上设置了一个应该处于活动状态的索引,就是这样.active 当列表元素的索引与 activeIndex 相同时添加 css 类.

You basically set an index that should be active and that's it. active css class is added when list element's index is the same as activeIndex.

对于在用户更改之前将activeIndex设置为现有选项,您可以在获取订阅数据到用户当前订阅时设置activeIndex.

As for setting activeIndex to existing choice before the user changes it, you can set activeIndex when fetching subscriptions data to user's current subscription.

小提琴:http://jsfiddle.net/eywraw8t/256701/

这篇关于VueJs 设置活动类,当一个 li 元素在 v-for 循环中单击时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆