In Vue.js, you can watch for changes to data properties by using the watch
option. Here's how you can do it:
watch
option in your Vue component:export default {
data() {
return {
message: 'Hello Vue!',
};
},
watch: {
// define watch function for 'message' data property
message(newValue, oldValue) {
console.log('message changed:', newValue, oldValue);
},
},
};
watch
option, define a function for each data property you want to watch. The function will be called whenever the watched property changes. It receives two arguments: the new value and the old value of the property.In the example above, whenever the message
data property changes, the message
watch function will be called, logging the new and old values of the property to the console.
Note that you can also use dot notation to watch for changes to nested data properties. For example, if you have a nested object user
with a property name
, you can watch it like this:
watch: {
'user.name': function(newValue, oldValue) {
console.log('user name changed:', newValue, oldValue);
},
},
In this case, the watch function will be called whenever the name
property inside the user
object changes.
That's how you can watch for changes to data properties in Vue.js using the watch
option.