简体   繁体   English

根据 Vue.js 中的 v-model 将类绑定到元素

[英]Bind class to element depending on v-model in Vue.js

Trying to create dynamic table( link to Codepen ) with Vue.尝试使用 Vue 创建动态表(链接到 Codepen )。 Now i want to add class using :class to row when checkbox is checked.现在我想在选中复选框时使用:class添加类到行。 Every checkbox is bound with specific value in object of objects.每个复选框都与对象对象中的特定值绑定。

<tbody>
      <tr v-for="row in filteredData" 
          :key="row.id" 
          :class="{'is-selected':checkboxes[row.id].checked}">
        <td>
          <input type="checkbox" v-model="checkboxes[row.id].checked"></td>
        <td>{{row.id}}</td>
        <td>{{row.name}}</td>
        <td>{{row.position}}</td>
        <td>{{row.salary}}</td>
      </tr>
    </tbody>

There is no error or warning, it just not working.没有错误或警告,它只是不工作。 I would be glad to hear any idea about solving this problem.我很高兴听到有关解决此问题的任何想法。

this is the problem:这就是问题:

this.checkboxes[data[index].id] = { id: data[index].id, checked: false };

the object property won't reactive when defined in this way.以这种方式定义时,对象属性不会反应。

in https://v2.vuejs.org/v2/guide/reactivity.html ,https://v2.vuejs.org/v2/guide/reactivity.html中,

Due to the limitations of modern JavaScript (and the abandonment of Object.observe), Vue cannot detect property addition or deletion.由于现代 JavaScript 的限制(以及 Object.observe 的废弃),Vue 无法检测到属性的添加或删除。

Vue does not allow dynamically adding new root-level reactive properties to an already created instance. Vue 不允许动态地将新的根级响应属性添加到已创建的实例中。 However, it's possible to add reactive properties to a nested object using the Vue.set(object, key, value) method但是,可以使用 Vue.set(object, key, value) 方法向嵌套对象添加反应属性

using .$set to set the object property would make it reactive.使用.$set设置对象属性会使其反应。

  createCheckboxArr: function(data) {
    for (let index = 0; index < data.length; index++) {
      this.$set(this.checkboxes, data[index].id, {
        id: data[index].id,
        checked: false
      });
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM