【问题标题】:Vuejs add and remove classes with v-forVuejs 使用 v-for 添加和删除类
【发布时间】:2019-01-15 07:35:04
【问题描述】:

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

items: [
   {
       foo: 'something',
       number: 60
   },
   {
       foo: 'anything',
       number: 15
   },
   {
       foo: 'text',
       number: 20,
   }
]

模板

<div v-for="(item,index) in items" :key="index">
     <div :class="{ active: ????}" @click="toggleActive">
          {{ item.foo }} 
          {{ item.number }}
     </div>
</div>

JS

methods: {
    toggleActive() {
        //
    }
}

我需要以下内容:当我单击 div 添加活动类时,如果我已经有活动类 - 删除活动类。(切换)。我也可以选择多个项目。

我该怎么做?我在 items 数组中没有布尔变量,我不应该在单独的组件中移动项目

【问题讨论】:

标签: javascript vue.js v-for


【解决方案1】:

App.vue

<template>
     <div>
        <div 
        v-for="(item, i ) in items" 
        :key="i"
        :class="{ active: i === activeItem}"
        >
         // some looped items from data here
         // button for active toggle 
            <button @click="selectItem(i)"> make item active </button>
        </div>
    </div>
</template>
 

数据和方法

<script>
export default {
    data() {
        return {
            activeItem: null,
        };
    },
    methods: {
        selectItem(i) {
            this.activeItem = i;
        },
    },
};
</script>

【讨论】:

    【解决方案2】:

    给你。

    new Vue({
      el: "#app",
      data: {
        items: [{
            foo: 'something',
            number: 60
          },
          {
            foo: 'anything',
            number: 15
          },
          {
            foo: 'text',
            number: 20,
          }
        ]
      },
      methods: {
        toggleActive(index) {
          let item = this.items[index];
    
          item.active = !item.active;
    
          this.$set(this.items, index, item);
    
        }
      }
    })
    .active {
      color: red;
    }
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
    <div id="app">
      <div v-for="(item,index) in items" :key="index">
        <div :class="{ active: item.active}" @click="toggleActive(index)">
          {{ item.foo }} {{ item.number }}
        </div>
      </div>
    </div>

    这是一个 JS Fiddle: https://jsfiddle.net/eywraw8t/250008/

    【讨论】:

    • 对了,我忘了添加从真到假和假到真的条件。但我想你已经知道该怎么做了。
    • 很简单:item.active = !item.active;
    猜你喜欢
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 2017-06-14
    • 1970-01-01
    • 2020-09-08
    • 2017-10-27
    相关资源
    最近更新 更多