Reputation: 47
I wonder why vue UPDATE changes to the page when I directly set an item with the index. Accrding to the official document, Vue is not able to detect changes to an array when I directly set an item with the index. My code was like
const app = new Vue({
el: '#app',
data(){
return {
title: 'Hello, world!',
courses: ['Math','Literature','CS']
}
},
mounted() {
setTimeout(()=>{
this.title = 'Hello, vue!';
this.courses[1] = 'Chemistry';
this.courses.push('Physical');
}, 3000);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app" v-cloak>
<h2 :title="title">
{{title}}
</h2>
<div v-for="c in courses" :key="c">
{{c}}
</div>
</div>
Upvotes: 1
Views: 31
Reputation: 1294
this.title = 'Hello, vue!';
and this.courses.push('Physical');
trigger render. Then vue creates a new Vnode, where the acquired this.courses[1]
has changed.
Try this.
const app = new Vue({
el: '#app',
data(){
return {
title: 'Hello, world!',
courses: ['Math','Literature','CS']
}
},
mounted() {
setTimeout(()=>{
// this.title = 'Hello, vue!';
this.courses[1] = 'Chemistry';
// this.courses.push('Physical');
}, 3000);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app" v-cloak>
<h2 :title="title">
{{title}}
</h2>
<div v-for="c in courses" :key="c">
{{c}}
</div>
</div>
Upvotes: 1
Reputation: 1448
Its because you are changing the :key of your looping template
<div v-for="c in courses" :key="c">
{{c}}
</div>
Here you have provided the array elements as key for vue to keep it in its change detection mechanism. So its reactivity is depending on the courses elements. Any change in those elements will trigger the change detection and thus the div will be updated.
If you don't want vue to change your looping elements on changing the data then I would say change your key. You can use array index for keys if you don't want any re-render but that's not a good idea.
<div v-for="(c, index) in courses" :key="index">
{{c}}
</div>
Check this resource to know more about re-render mechanism in vue: https://michaelnthiessen.com/force-re-render/
Upvotes: 0