4

Vue app uses v-for for rendering the array or list normally.
This is an example.
JsFiddle Example

 new Vue({
  el:'#mainapp',
  data:{
    items:[0,0, 0]
  },
  methods:{
    updateVaule:function(index){
      this.items[index]++;
      alert('current value'+this.items[index]);
    }
  }
})

//Html file
    <div id="mainapp">
      <span v-for="(item,index) in items" v-on:click="updateVaule(index)">{{item}}</span>
    </div>

But when the user clicking the span tag, the view is not updated though value of items had been changed.
I've tried to add v-bind:key=index to the span tag, but this didn't affect anything.
To render the updated array, how does the app have to work?
What am I wrong?

2
  • @GhostCat, what do I have to do? Commented Oct 5, 2018 at 8:57
  • I appreciate the quick comeback. In this example, the question should have been closed, as off topic for example. It really doesn't belong on SO. So, I am only asking to be really thoughtful when voting EDIT on triage. You see, if the majority votes "edit", then others are asked to edit. Which is pointless with questions that can't be fixed by editing. That is all there is to this. I hope that makes sense? Commented Oct 5, 2018 at 9:12

1 Answer 1

3

You can use Vue's $set method to change the array elements.

new Vue({
  el:'#mainapp',
  data:{
    items:[0,0, 0]
  },
  methods:{
    updateVaule:function(index){
      this.$set(this.items, index, this.items[index] + 1)
      alert('current value'+this.items[index]);
    }
  }
})

Fiddle

More info on $set method and reactivity in depth here

Sign up to request clarification or add additional context in comments.

1 Comment

As explained in Common Beginner Gotchas(vuejs.org/2016/02/06/common-gotchas/…), you should use array methods like push, splice or whatever and never modify the indexes like this a[index] = 1 nor the .length property of an array. Since the abandonment of Object.observe and Array.observe, vue can't pick the changes made the way you did (here is where the $set method comes in).

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.