[Vuejs]-Vuejs Updating v-for by reference

0👍

When this.result = result, this.result points to one address of the memory.

When <result-update v-if="result" v-model="result"> receives input event then assign new value to this.result, it will make this.result = newValue (actually point to another address of the memory for newValue), so it will not change the value for result[index] as you expected.

Check below demo:

const test = {result: []}
let value1 = ['a']
console.log('org', test)
test.result = value1 // assign with new array
console.log('Replace the whole array', test)
value1[0] = 'b' // assign new value to first element of value1
console.log('Update one item of the array', test) //test.result and value1 point to same address of the memory

The solution:

You can save the index for current <result-index>, then change the value by this.results[index].

So adjust your codes to below then should work fine.

For the template of component <result-index>, change it to:

<result-index>
    <li v-for="(result, index) in results" @click="getReult(index)">
        {{ result.name }}
     </li>
</result-index>

For the method=getResult inside component <result-index>, change it to:

methods: {
    getResult: function(index) {
        this.selected = index;
    }
}

Inside the parent component, change the template to:

<result-update v-if="selected >= 0" v-model="results[selected]">
 //... here is a form to access the result and update it
</result-update>

Leave a comment