Vue-router component reusing

我的梦境 提交于 2020-05-29 03:23:29

问题


I would like to know how can I stop component reusing in Vue-router.

I'm building a simple page application and I am unable to update data after clicking the same link twice.

Is it possible to somehow force reloading or what are the best practices in my situation?


回答1:


Use the key attribute on router-view set to current url. It's built in, so no need to write any code.

<router-view :key="$route.fullPath"></router-view>



回答2:


Vue Router reuses the same component therefore the mounted hook won't be called. As stated in the documentation:

The same component instance will be reused [...] the lifecycle hooks of the component will not be called.

If you want to update the data you have two options:

  • Watch the $route object

const User = {
  template: '...',
  watch: {
    '$route' (to, from) {
      // react to route changes...
    }
  }
}
  • Use the beforeRouteUpdate navigation guard

const User = {
  template: '...',
  beforeRouteUpdate (to, from, next) {
    // react to route changes...
    // don't forget to call next()
  }
}

For a more detailed explanation you can check the section Reacting to Param Changes of the Vue Router documentation: https://router.vuejs.org/guide/essentials/dynamic-matching.html#reacting-to-params-changes.




回答3:


One way to do this is to put a key on the router-view and append a timestamp querystring to your router-link

const Home = {
    template: '<div>Home</div>',
    created() {
        console.log('This should log everytime you click home.');
    },
};

const router = new VueRouter({
    mode: 'history',
    routes: [
        { path: '/', component: Home },
    ]
});

new Vue({
    router,
    el: '#app',
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>


<div id="app">
  <router-link :to="`/?q=${Date.now()}`">/home</router-link>
  <router-view :key="$route.fullPath"></router-view>
</div>

One reason not to do it this way is because it'll force rerenders on components that you may want to be reused such as on routes like

  • /posts/1
  • /posts/2


来源:https://stackoverflow.com/questions/52505126/vue-router-component-reusing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!