Search code examples
vue.jsvuejs2v-for

Change specific index without re-render whole array in Vuejs


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.


Solution

  • 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();
    }