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
Say we want to get our data immediately when the component mounts. We then add the
mounted lifecycle method into our component.
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
id prop for changes.
By defining a
watcher, we tell our component to call the
getData method whenever the
id prop is changed.
Our component works just fine as it is right now. However, how can we rewrite it to be more concise?
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!