Quick Vue Tip: Fetching Data
A common use-case we encounter is needing to show data fetched from an API using a Vue component.
For example, say we have a Vue component called ViewAvenger.vue
which shows the information of an Avenger based on its id. A common way of doing this is by passing an id
prop to our component. The actual API call is then handled by the component itself via a method call getData
.
Loading data upon mount
Say we want to get our data immediately when the component mounts. We then add the mounted
lifecycle method into our component.
Re-load data if the id
changes
This works fine, but what if our id
prop changes? There would be no way for us to call getData
. To do that, we would need to watch
the id
prop for changes.
By defining a watcher
, we tell our component to call the getData
method whenever the id
prop is changed.
Refactoring for simplification!
Our component works just fine as it is right now. However, how can we rewrite it to be more concise?
We use watch
props!
Watchers can have the immediate
prop, which tells the component to fire the handler method immediately. This means that we can get rid of the mounted
method, saving us some lines of code.
Finally, we can simplify this even further! We can move our whole getData
function into the watch handler. As an added bonus to readability, we can remove the this.
prefix from the API call since we can simply use the id
argument of the handler function!
And just like that, we effectively saved ourselves some more lines of code.
I hope you found this tip useful, and thanks for reading!
Top comments (8)
Great tip Miguel. You can also use this to watch the route or route params if your avenger id was coming from the route (/avengers/3). You just need to put it in quotes like this:
Yes! Applying this to your Vue routes is the logical extension for this pattern, and is how I use it in my apps as well. Thank you for sharing, Dan!
Thanks for sharing this Dan, sometimes var manipulation can be very tricky
Great Tip!!
Thanks for sharing it. Just like you read my mind.
Thanks for this. For routing params, I made them component props and watch the props. I found this article because I wanted to confirm if it's good practice to fetch data in just the watcher and not in
created
as well. Makes sense to do it in just the watcher usingimmediate
, unless other setup needs to be done when the component is created before making the api call.Happy to hear it helped!
Very nice. I haven't used watchers that much, but this pattern seems like a great way to simplify this fetching of data. Thanks for writing :)
You're very welcome, thank you for reading!