v-for中的Vue.js切换类 [英] Vuejs toggle class in v-for

查看:103
本文介绍了v-for中的Vue.js切换类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用v-for循环列出项目。我有一些来自服务器的API数据。

I'm making a list of items with v-for loop. I have some API data from server.

items: [
   {
       foo: 'something',
       number: 1
   },
   {
       foo: 'anything',
       number: 2
   }
]

我的模板是:

<div v-for(item,index) in items @click=toggleActive>
     {{ item.foo }} 
     {{ item.number }} 
</div>

JS:

methods: {
    toggleActive() {
        //
    }
}

我如何使用:class = {active:something}切换活动类?
PS我的项目中没有布尔值

How can i toggle active class with :class={active : something} ? P.S I don't have boolean value in items

推荐答案

您可以尝试实现以下内容:

You can try to implement something like:

<div 
  v-for="(item, index) in items"
  v-bind:key="item.id" // or alternativelly use `index`.
  v-bind:class={'active': activeItem[item.id]}
  @click="toggleActive(item)"
>

JS:

data: () => ({ 
  activeItem: {}, 
}),

methods: {
  toggleActive(item) {
    if (this.activeItem[item.id]) {
      this.removeActiveItem(item);

      return;
    }

    this.addActiveItem(item);
  },
  addActiveItem(item) {
    this.activeItem = Object.assign({},
      this.activeItem,
      [item.id]: item,
    );
  },
  removeActiveItem(item) {
    delete this.activeItem[item.id];
    this.activeItem = Object.assign({}, this.activeItem);
  },
}

这篇关于v-for中的Vue.js切换类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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