2

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?

1 Answer 1

4

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]);
}
Sign up to request clarification or add additional context in comments.

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.