将样式应用于特定的 v-for 元素

Apply styles to specific v-for element

我正在制作一个简单的待办事项列表应用程序,想知道如何在 特定动态 v-for 元素上应用样式。

<f7-list-item v-for="(listItem, index) in activeList.listItems" :key="index" :class="(checked) ? 'checked':'not-checked'">
 {{ index+1 }}. {{ listItem }}
  <span @click="checkTaskDone(index)">
    <i class="f7-icons" id="check-task-btn">check_round</i>
  </span>
</f7-list-item>
export default {
 data() {
  return {
   checked: false
  }
 },
 methods: {
  checkTaskDone(item) {
   if (this.checked == false) {
    this.checked = true;
   } else if (this.checked == true) {
    this.checked = false;
   }
  }
 }
}
.checked {
 text-decoration: line-through;
 color: #444;
}

使用此代码,它会按预期将 class 添加到每个 v-for 列表元素,而不管单击哪个元素。我想知道处理这个问题的最佳方法是什么。我已经尝试从 index 制作道具并尝试将其作为应用样式的目标,但我无法使其工作。

提前致谢!

通常您希望在单个待办事项上有一个 "done" 或 "checked" 标志,例如:

const todoList = [
  {
    name: 'Grab some food',
    done: false
  },
  {
    name: 'Start coding',
    done: false
  }
];

并且在 Vue.js 中,您可以使用 v-bind:class 而不是三元运算符来执行 class 切换:

export default {
  data() {
    return {
      //checked: false,

      activeList: {
        listItems: [
          {
            name: 'Grab some food',
            done: false
          },
          {
            name: 'Start coding',
            done: false
          }
        ]  
      }
    }
  },
  methods: {
    checkTaskDone(item) {
      //if (this.checked == false) {
      //  this.checked = true;
      //} 
      //else if (this.checked == true) {
      //  this.checked = false;
      //}

      // Check/uncheck
      item.done = !item.done;
    }
  }
}
<f7-list-item 
  v-for="(listItem, index) in activeList.listItems" 
  :key="index"
  :class="{ 'checked': listItem.done }">

 {{ index + 1 }}. {{ listItem }}

  <span @click="checkTaskDone(listItem)">
    <i class="f7-icons" :id="`check-task-btn${index}`">check_round</i>
  </span>
</f7-list-item>

顺便说一句,我在单个 i.f7-icons 元素上附加了一个索引,因为 ID 应该是唯一的,否则请改用 class

首先你需要根据activeList.listItems长度创建动态检查数组!然后你可以检查索引,你可以通过 this.$set(array,index,value) ...

更新数组数据

new Vue({
 el: "#app",
 data: {
   checked: [],
   activeList : {listItems:[1,2,3,5]}
 },
 created: function() {
   for(var i = 0; i < this.activeList.listItems.length; i++) {
     this.checked.push(false);
   }
 },
 methods: {
  checkTaskDone(item) {
   if (this.checked[item] == false) {
    this.$set(this.checked,item, true);
   } else if (this.checked[item] == true) {
    this.$set(this.checked,item, false);
   }
  }
 }
 });
.checked {
 text-decoration: line-through;
 color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(listItem, index) in activeList.listItems" :key="index" :class="{checked: checked[index]}">
 {{ index+1 }}. {{ listItem }}
  <span @click="checkTaskDone(index)">
    <i class="f7-icons" id="check-task-btn">check_round</i>
  </span>
</div>

</div>