2

In a Vuejs project, I have an array in my data object and render it in view with a v-for directive. now if I change a specific index in that array, Vue re-render the whole array in view. is there any way to see changes in view without re-render the whole array?


the reason behind this question is that other indexes of my array processing or doing something and when the whole array re-render in view, these processes are stopped.

2
  • Can you add what ever code you tried so far .. Commented Aug 25, 2020 at 13:44
  • codes don't explain anything more than these words in this question my friend Commented Aug 25, 2020 at 17:49

1 Answer 1

1

In Vue 1.x we have track-by="$index" to track changed index in rendered array. but since version 2.x, Vue suggest using :key when we rendering array in view with v-for intead track-by="$index". but consider this blow example:

In <template> :

<div v-for="(doc, i) in docs" :key="i">
 <h4>{{ doc.status }}</h4>
 <button @click="reject(i)"> Reject </button>
</div>

In <script> :

data: {
 docs: [
  { status: 'pending' },
  { status: 'pending' },
  { status: 'pending' }
 ]
},

methods: {
 reject(index) {
  this.docs[index] = { status: 'rejected' }
 }
}

in this example, when we change an index, Although array changes but we can't see any change in view. that's because our component rendered before and we need to update its view. for this we need to use this.$forceUpdate() in our method to update the component.

reject(index) {
 this.docs[index] = { status: 'rejected' }
 this.$forceUpdate();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Downvoting as most of this (self)answer is simply wrong. First: reason the Vue does not update the view after above array change is that Vue 2 can't detect change when you directly set an item with the index - see Change Detection Caveats For Arrays. Second: key is important yes, but it does not change the fact that if you have a v-for over an array in the template, it always renders all items in the array. See my answer to similar question for more details...

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.