Home > Software engineering >  index in v-for for array v-if not updating - Vue.js
index in v-for for array v-if not updating - Vue.js

Time:02-23

I've created a simple vue.js program that uses a for loop to toggle the visibility of text. I have a button that should toggle it, but when it is clicked, it changes the variable but doesn't update the button.

let app = new Vue({
  data() {
    return {
      array: [true,true,false],
      text: ["0","1","2"]
    }
  },
  methods:{
    change(index){
      this.array[index]=!this.array[index]
      console.log(this.array[index],index)
    }
  },
  el: "#app"
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(item,index) in text">
    <button @click="change(index)">toggle show</button>
    <a v-if="!array[index]">...</a>
    <a v-else>{{item}}</a>
  </div>
</div>

Is there any way I could get this simple app to work without changing the arrays?

CodePudding user response:

You’re running into a reactivity caveat: you cannot update a specific entry in an array by index in that way.

You’ll need to use Vue.set or this.$set (the latter is simply an alias for the former):

change(index){
  this.$set(this.array, index, !this.array[index]);
}
  • Related