DEV Community

David Berri
David Berri

Posted on • Originally published at dberri.com on

1 1

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()
  }
}
Enter fullscreen mode Exit fullscreen mode

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
  }
}
Enter fullscreen mode Exit fullscreen mode

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:

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay