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

标签 javascript css list vue.js html-framework-7

我正在制作一个简单的待办事项列表应用程序,想知道如何在特定的动态 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;
}

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

提前致谢!

最佳答案

通常您希望在单个待办事项上有一个“完成”或“已检查”标志,例如:

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

在 Vue.js 中,您可以使用 v-bind: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

关于javascript - 将样式应用于特定的 v-for 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54879313/

相关文章:

list - Haskell将值赋给理解内的变量

javascript - 使用 Javascript 将结构化字符串转换为数组

css - javafx 和 css 代码更改鼠标悬停时的超链接颜色

html - 目录 XSL

css - 如何使用 CSS 使列表项保持在一起?

python - AttributeError : 'list' object has no attribute 'isdigit' . 有效指定句子列表中每个单词的 POS?

javascript - Angular 2 选择选项(下拉)-如何获取更改值以便在函数中使用它?

javascript - 在 Electron 应用程序之外粘贴或以其他方式输出文本?

javascript - 更新 JavaScript 时遇到问题

javascript - 有什么方法可以在 Magento 1411 上调试 Lightbox2