Vue JS v-for Updating Components
How to use .#set to maintain reactivity.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.24/vue.js"></script>
<div id="app">
<container></container>
</div>
<template id="container">
<h1>Vue JS v-for Updating Components</h1>
<p>If you think you're having reactivity problems in Vue JS, try using .$set instead!</p>
<p>This a component which contains 3 components generated by v-for. If the props of the contained components are naively updated, then reactivity won't work. Use .$set instead! </p>
<p>More info <a target="_blank" href="http://vuejs.org/guide/list.html#Caveats">here</a>.</p>
<button @click="changeMessages">Change the Messages Without .$set</button>
<button @click="changeMessagesSet">Change the Messages With .$set</button>
<button @click="toConsole">Send Messages to Console</button>
<inner :messages="messages"></inner>
</template>
<template id="inner">
<p v-for="message in messages">{{ message.text }}</p>
</template>
JavaScript
Vue.component('container', {
template: '#container',
data: function() {
return {
messages: [{ text: 'Message 1' }, { text: 'Message 2' }, { text: 'Message 3' }],
messageStatus: '',
}
},
methods: {
changeMessages: function() {
this.messages[0] = { text: 'CHANGED MESSAGE 1 WITH SET'};
this.messages[1] = 'CHANGED MESSAGE 2 WITHOUT SET';
this.messages[2] = 'CHANGED MESSAGE 3 WITHOUT SET';
},
changeMessagesSet: function() {
this.messages.$set(0, { text: 'CHANGED MESSAGE 1 WITH SET'});
this.messages.$set(1, { text: 'CHANGED MESSAGE 2 WITH SET'});
this.messages.$set(2, { text: 'CHANGED MESSAGE 3 WITH SET'});
this.$set(this.messages, 3, 'CHANGED MESSAGE 4 WITH SET');
},
toConsole: function() {
for (let message of this.messages) {
console.log(message);
}
}
}
});
Vue.component('inner', {
template: '#inner',
props: {
messages: Array,
},
watch: {
messages() {
}
},
});
new Vue({
el: '#app',
});