Smarter Vue Watchers
In some Vue projects, you might need to load data from an API as soon as the component is instantiated and load new data once a value or property of the component is changed. For example, when you use a search input field. I've done that several times, and always used the following pattern:
// Inside a Vue component
created() {
this.search()
},
watch: {
searchInput() {
this.search()
}
}
And that's ok, it works well. But then I found a simpler, more elegant way to do the same thing:
// Inside a Vue component
watch: {
searchInput: {
handler: 'search',
immediate: true
}
}
This code can replace the previous one entirely. That works because a watcher can receive an object, instead of a function, and this object contains a handler, which is the method to be executed when the watcher is notified, and the property immediate, which ensures that this method is also executed as soon as the component is in the lifecycle hook created
.
This tip was extracted from a video of a talk by Chris Fritz, one of the members of Vue.js' core team. Here's the video: