When navigating to the same component in Vue, it will reuse the instance and not re-run the created
hook. However, you can force it to run again by adding a key to the <router-view>
:
<router-view :key="$route.fullPath" />
Alternatively, you can utilize the beforeRouteUpdate
hook:
beforeRouteUpdate(to, from, next) {
if (this.$route.query.q) {
//fetchdata
}
next();
}
The beforeRouteUpdate
hook does not execute on initial component creation, so using both created
and beforeRouteUpdate
may be necessary.
Key differences:
With the key approach, the component is not cached and will be recreated on every route change, triggering the created
hook each time. This may be useful if you need to perform an action only once in the created hook, like calling an API regardless of query parameters. In rare cases, there could be performance implications from constant recreating.
Using beforeRouteUpdate
might require duplicating logic across two lifecycle hooks, but it allows for rerouting within the hook, offering additional flexibility.
Choose the method that aligns with your preferences and understanding of these distinctions.