Vue 2.x non-clicked checkbox are checked

Viewed 139

I am encountering this strange behavior in my code in Vue 2

What I am trying to achieve here is when I clicked on one of the checkbox, other checkbox(es) are checked as well. I only want the selected checkbox to be checked only. Is there a way to do so?

this is my component

           <div v-for="(item,index) in api[0].choice" :key="index">
              <input type="checkbox" @change="detect" v-model="option[index].checked">
              <label>{{item}}</label>
            </div>

data(){}

option: null,

mounted(){}

this.option = Array(this.api[0].choice.length).fill({checked: false})
1 Answers

Array.prototype.fill() passes a reference and not a new instance. So essentially all of your items inside of your array are mapped together. Thus when index n changes so do all the other values.

The easiest way to fix this, is to fill with undefined, by not passing an argument to fill, and then update the array, mapping the same object over and over again. Thus creating new instances of the object, instead of referencing the original object.

this.option = Array(5)
      .fill()
      .map((x) => ({ checked: false }));

Example on codesandbox


If you are expecting to have really large arrays .map() will be inefficient. Use a for loop instead

this.option = new Array(5);
for (let i = 0; i < 5; i++) {
    this.option[i] = { checked: false };
}
Related