Skip to content
Advertisement

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

Trying to create dynamic table( link to Codepen) with Vue. Now i want to add class using :class to row when checkbox is checked. 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.

Advertisement

Answer

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,

Due to the limitations of modern JavaScript (and the abandonment of Object.observe), Vue cannot detect property addition or deletion.

Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it’s possible to add reactive properties to a nested object using the Vue.set(object, key, value) method

using .$set to set the object property would make it reactive.

  createCheckboxArr: function(data) {
    for (let index = 0; index < data.length; index++) {
      this.$set(this.checkboxes, data[index].id, {
        id: data[index].id,
        checked: false
      });
    }
  }
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement