When are watch methods triggered?
Why is the watch method for the property initTasks being triggered?
by Roland Doda
HTML
<div id="app">
<customcomponent :init-tasks="tasks" :init-estimate="estimate"></customcomponent>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
ul {
list-style: square;
margin-left: 1em;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
del {
color: rgba(0, 0, 0, 0.3);
}
.tiny {
font-size: 0.75em;
line-height: 2em;
margin-bottom: 2em;
}
button {
margin: 1em 0 0;
}
Vue
Vue.component('customcomponent', {
props: ['initTasks', 'initEstimate'],
data() {
return {
tasks: [],
estimate: 0,
}
},
template: `
<div>
<ul>
<li v-for="(task, index) in tasks" :key="index">
{{task.text}}
</li>
</ul>
<p class="tiny">It will take you {{estimate}} hours to do all of these!</p>
<button @click="addTask">Add task</button>
</div>
`,
methods: {
initialize() {
this.tasks = this.initTasks.slice();
this.estimate = this.initEstimate;
},
addTask() {
Vue.set(this.tasks, this.tasks.length, {
text: "Do this new task",
done: false
});
this.estimate++;
}
},
watch: {
initTasks: function(oldval, newval) {
console.log('watch for initTasks triggered!');
this.initialize();
}
},
mounted() {
console.log('mounted() triggered!')
this.initialize();
},
created() {
console.log('created() triggered!')
},
updated() {
console.log('updated() triggered!')
},
destroyed() {
console.log('updated() triggered!')
}
});
new Vue({
el: "#app",
data: {
tasks: [
{ text: "Learn JavaScript", done: false },
{ text: "Learn Vue", done: false },
{ text: "Play around in JSFiddle", done: true },
{ text: "Build something awesome", done: true }
],
estimate: 5
}
});