vue on prop change code example
Example 1: vue watch props
new Vue({
el: '#app',
data: {
text: 'Hello'
},
components: {
'child' : {
template: `<p>{{ myprop }}</p>`,
props: ['myprop'],
watch: {
myprop: function(newVal, oldVal) {
console.log('Prop changed: ', newVal, ' | was: ', oldVal)
}
}
}
}
});
Example 2: vuejs change prop value
methods: {
add() {
this.$emit('add-counter', this.taskId);
}
}
<task-template
:task-name="task.name"
:task-id="task.id"
:task-counter="task.counter"
@add-counter="addTaskCounter"
>
</task-template>
data() {
return {
task: {
id: 0,
name: 'Empty been',
counter: '2'
}
}
}
methods: {
addTaskCounter(taskId) {
const identifiedTask = this.tasks.find((task) => task.id === taskId);
identifiedTask.counter += 1;
}
}
Example 3: how to watch for changes within a prop in vue
watch: {
$props: {
handler() {
this.parseData();
},
deep: true,
immediate: true,
},