VueJS v-if = array[index] is not working VueJS v-if = array[index] is not working vue.js vue.js

VueJS v-if = array[index] is not working


The problem is not about v-if, it's because Vue cannot detect the changes of an array element directly, this is one of the limitation of JavaScript.

Thus, Vue provides some helper functions for this, like Vue.set

Change this this.show[index] = !this.show[index]

to Vue.set(this.show, index, !this.show[index])

then it should work.

Vue.set is not the only solution, there are several ways to accomplish this, in case you may want to know.

You can use native methods of JavaScript array, Vue will hook on these methods so it can detect the changes.

Here is the example of the usage of .splice

this.show.splice(index, 1, !this.show[index])

Another way is to replace the array entirely. If you are using ES6, you can use the spread operator to clone the array easily:

this.show[index] = !this.show[index]this.show = [...this.show]

.map will also work because it returns a new array

this.show = this.show.map((el, i) =>  i === index ? !el : el)


You can use a JS object instead of an array and get the same effect. In other words, replace show: [false, false, false], with show: {0:false, 1:false, 2:false},.


In component in methods you can use:

this.$set(this.show, index, !this.show[index])