Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

javascript - Created hook not running again when pushing the same route with a new query

I have a component with a created hook like this:

created() {
    if (this.$route.query.q) {
        //fetchdata
    }
}

However within the same component I try doing $router.push(`?q=${search}`) and the URL changes but the created hook doesn't rerun.

question from:https://stackoverflow.com/questions/65872591/created-hook-not-running-again-when-pushing-the-same-route-with-a-new-query

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...