In Vue.js, the “watcher” refers to a feature that allows you to watch for changes in a specific property of a Vue instance or a component. Watchers are used to perform custom logic when the watched property changes. They are particularly useful when we need to react to changes in data and perform actions, such as making an API call, updating other properties, or triggering animations.
example:
// Vue component
Vue.component('example-component', {
data() {
return {
message: 'Hello, Vue!'
};
},
watch: {
message(newMessage, oldMessage) {
console.log(`Message changed from ${oldMessage} to ${newMessage}`);
// Perform custom logic here
}
}
});
In this example, a watcher is set up for the message property. Whenever the message changes, the function specified in the watcher will be invoked with the new and old values of the property. We can then use this function to perform any necessary actions based on the change.