<template>
<div
v-for="(a, i) in arr"
:key="i"
:checked="a"
@click="toggleItem(i)"
>
<div >{{ arr }}</div>
</template>
<script>
export default {
data() {
return {
arr: [true, false, true, false, true, true, true],
};
},
methods: {
toggleItem(index) {
this.arr.splice(index, 1, !index);
}
};
</script>
I wonder why the array arr is not rerendered in the template, probably because of the vue reactivity issues ?
I would like to receive rerendered {{arr}} in the template with opposite array items, changed from true to false and false to true.
CodePudding user response:
Index is a number, so given this line of code:
this.arr.splice(index, 1, !index);
If say index
= 3, then !index
= false (so says JavaScript when you negate any number), meaning the line of code can be simplified to:
this.arr.splice(index, 1, false);
Instead you need to specify the index of the array:
this.arr.splice(index, 1, !this.arr[index])
Here's a sandbox example.