首页 > 解决方案 > 为什么 v-bind 属性不能正常工作?

问题描述

所以我正在使用 VueJS 创建一个简单的待办事项列表应用程序:

<template>
    <div>
      <br/>
      <div id="centre">
        <div id="myDIV" class="header">
          <h2 style="margin:5px">My To Do List</h2>
          <input type="text" id="myInput" v-model="text" v-on:keyup.enter="AddNote()" placeholder="Title...">
          <span v-on:click="AddNote()" class="addBtn">Add</span>
        </div>

        <ul id="myUL">
          <li v-on:click="ToggleClass(index)" v-for="(item, index) in array" v-bind:class="{ checked: isChecked[index] }">
            {{item}}
            <span class="close">×</span>
          </li>
        </ul>
      </div>
    </div>
</template>

<script>
    export default {
        name: "Notepad",

        data() {
          return {
            array: [],
            text: "",
            isChecked: []
          }
        },

        methods: {
          AddNote: function() {
            if(this.text!=="") {
              this.array.push(this.text);
              this.isChecked.push(false);
              this.text = "";
            }
          },

          ToggleClass(index) {
            console.log(index);
            this.isChecked[index]=!this.isChecked[index];
            console.log(this.isChecked);
          }
        }
    }
</script>

但是,当我单击一个项目时,当我单击它时 v-bind 属性不会绑定该类。相反,当我在上面的文本字段中输入内容时,它会绑定它。

有人可以帮忙吗?

标签: javascriptvue.js

解决方案


数组不是响应式的isChecked,vue 无法检测到更改。您必须触发它,例如通过$setsplice

在此处阅读更多信息:https ://vuejs.org/v2/guide/list.html#Caveats

您可以像这样更改代码:

ToggleClass(index) {
  console.log(index);
  this.isChecked.splice(index, 1, !this.isChecked[index])
  // or this.$set(this.isChecked, index, !this.isChecked[index])
  console.log(this.isChecked);
}

推荐阅读