1

I am using Vuetify checkbox (which I don't think is relevant, this is probably caused by Vue itself), and trying to get an array of checkbox double binding with an array of true, false value. By controlling the true/false value of each element, I want to control the checking status of the checkbox. Here is an example code in fiddle that WORKS with a SINGLE element:

HTML:

<v-checkbox v-model="selected" label="John">      </v-checkbox>
<v-btn @click="toggle">toggle</v-btn>

Script:

toggle () {
    this.selected=!this.selected
    console.log(this.selected)
    }

This works: https://jsfiddle.net/ziranshu/evsatguy/12

However, when I put the v-model values into an array: html:

<v-checkbox v-model="selected[0]" label="John">      </v-checkbox>
<v-btn @click="toggle(0)">toggle John</v-btn>

script:

toggle (index) {
    this.selected[index]=!this.selected[index]
    console.log(this.selected)
}

It's NOT working anymore: https://jsfiddle.net/ziranshu/evsatguy/20

I can't think of any difference between binding with an array element and binding with a single value. Can anyone explain, and suggest how to fix this?

1
  • yes, reactivity within an array is tricky. If you need to use an array there are some ways to get around it. Commented Apr 11, 2019 at 15:51

2 Answers 2

3

The issue is that you need to use $set method becasue you are dealing with an array

instead of

new Vue({
  el: '#app',
  methods: {
    toggle (index) {
      this.selected[index]=!this.selected[index] // <== no-no for array
      console.log(this.selected)
    }
  },
  data() {
    return {
      selected: [false,false]
    }
  }
})

use:

new Vue({
  el: '#app',
  methods: {
    toggle (index) {
      this.$set(this.selected, index,!this.selected[index] ) // <== yes-yes for arrays and objects
      console.log(this.selected)
    }
  },
  data() {
    return {
      selected: [false,false]
    }
  }
})

this will trigger the reactivity.

I recommend reading this reactivity page from the vue docs which explains the why and how.

Sign up to request clarification or add additional context in comments.

1 Comment

great answer, especially including vues reactivity page
1

For a purely javascript fix, without needing vues internals, you can copy the array, update the value you want then reset selected:

toggle (index) {
  let selected = this.selected.slice(0)
  selected[index] = !selected[index]
  this.selected = selected
}

This will trigger vues internal reactivity to update the template and data accordingly

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.