Vue will reuse the component if you re-route to it, so created
won't run again. You can force it to do so with a key on the <router-view>
:
<router-view :key="$route.fullPath" />
or use the beforeRouteUpdate
hook:
beforeRouteUpdate(to, from, next) {
if (this.$route.query.q) {
//fetchdata
}
next();
}
This hook won't run when the component is first created, so with this solution you may need to use both created
and beforeRouteUpdate
.
Some differences:
With the key solution, the component won't be cached so it will be recreated on each route (which is what causes created
to run each time). Maybe you wouldn't want that if you needed to do something only once in created such as calling an api only once regardless of the query. Or in rare cases maybe there would be a performance implication to recreating (probably not).
With beforeRouteUpdate
you may have to use the same logic in 2 lifecycle hooks, but that's not really a problem. You can also reroute from this hook, which might be useful.
Use whichever one you prefer / makes more sense, as long as you understand the differences.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…