How to deep watch an array of objects in Vue.js
In this tutorial, we are going to learn about how to watch an array of objects in Vue.js with the help of examples.
Consider we have an array of objects like this.
const users = [
{ id: 1, name: "John" },
{ id: 2, name: "seal" },
{ id: 3, name: "king" }
]
Now we need to watch any change happens in each object of a users
array.
Getting started
First, we need to create a new component called User.vue
where it handles each user data.
<template>
<p>{{user.id}}: <input v-model="user.name"></p></template>
<script>
export default {
props: ["user"]};
</script>
Now, let’s use the above component by passing a users
array data inside the App.vue
file.
<template>
<div id="app">
<div v-for="user in users" :key="user.id">
<User :user="user"/> </div>
</div>
</template>
<script>
import User from "./components/User";
export default {
name: "App",
data() {
return {
users: [
{ id: 1, name: "John" },
{ id: 2, name: "seal" },
{ id: 3, name: "king" }
]
};
},
components: {
User
}
};
</script>
Now, we need to detect any change happens on each user
inside the User.vue
component.
<template>
<p>{{user.id}}: <input v-model="user.name"></p>
</template>
<script>
export default {
props: ["user"],
watch: {
"user.name": function(newVal, previousVal) { console.log("new Value is " + newVal, "previous value is " + previousVal); } }
};
</script>
In the above code, we have used "user.name"
property instead of user
so that vue can detect any change happens in the user.name
property.
Let’s test it.
Similarly, you can also watch objects by adding deep: true
but in that case, we didn’t get any previous value.
<template>
<p>{{user.id}}: <input v-model="user.name"></p>
</template>
<script>
export default {
props: ["user"],
watch: {
user: {
handler:function(newVal) {
console.log("new Value is " + newVal) },
deep:true },
}
};
</script>