I have a Vue.js component where I need to run a function whenever a property inside an object changes.
My component looks like this:
<template>
<div>
<input v-model="user.name" />
<p>{{ user.name }}</p>
</div>
</template>
<script>
export default {
data() {
return {
user: {
name: '',
email: ''
}
}
},
watch: {
user(newValue, oldValue) {
console.log('User changed:', newValue)
this.saveUser()
}
},
methods: {
saveUser() {
console.log('Saving user...')
}
}
}
</script>
The user.name value changes correctly in the template, but the user watcher does not run when I change the input.
I tried watching the object directly because I want to detect changes to any property inside user.
What is the correct way to watch nested properties in Vue.js?
Should I use a deep watcher such as:
watch: {
user: {
handler(newValue) {
this.saveUser()
},
deep: true
}
}
Are there any performance concerns with using deep: true if the object contains many nested properties?
What would be the recommended approach for this situation?