<template>
<div>
<h2>Array Watcher</h2>
<ul>
<li v-for="item in array" :key="item.id">
{{ item.name }}
</li>
</ul>
<button @click="updateArray">Update Array</button>
<h2>Object Watcher</h2>
<p>{{ object.name }} - {{ object.age }}</p>
<button @click="updateObject">Update Object</button>
</div>
</template>
<script>
export default {
data() {
return {
array: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
],
object: { name: 'John', age: 30 },
};
},
watch: {
array(newArray, oldArray) {
console.log('Array changed:', newArray, oldArray);
},
'object.name': {
handler(newName, oldName) {
console.log('Object name changed:', newName, oldName);
},
deep: true,
},
'object.age': function (newAge, oldAge) {
console.log('Object age changed:', newAge, oldAge);
},
},
methods: {
updateArray() {
this.array.push({ id: 4, name: 'Item 4' });
},
updateObject() {
this.object.name = 'Jane';
this.object.age = 35;
},
},
};
</script>