Home > Software design >  Vue-router is changing the url but not re-rendering the component
Vue-router is changing the url but not re-rendering the component

Time:10-20

First of all I've checked and history mode is turned on, I invoke vue-router like so:

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: routes,
});

The current route I am on is /page/item/8, and I am redirecting to /page/item/9. Currently the url changes but the page does not re-render leaving me on the same view I had before.

This redirection is done like so:

this.$router.push({ name: 'PageItem', params: { itemId: '9' }}).catch(err => {
  // Stop Vue.router throwing an error if a user clicks on a notification with the same route.
  if (err.name !== 'NavigationDuplicated') {
    this.$logger.debug.log(err);
  }
});

The route in question like so:

import PageWrapper from '@/layouts/PageWrapper';
    
export default [
  {
    path: '/page',
    name: 'page',
    component: PageWrapper,
    children: [
      ... Other Routes ...
      {
        component: () => import(/* webpackChunkName: "page-item" */'@/pages/PageItem'),
        name:      'PageItem',
        path:      '/item/:itemId/:view?',
      },
    ],
  },
];

Any ideas, I've tweaked the code to remove identifying code so apologies if it looks a bit odd.

CodePudding user response:

Only the itemId route param is changing. In this situation, since the same route components are being used before and after the transition, vue-router will reuse the existing route components; they don't get destroyed and recreated. So if you're loading data in the component created or mounted hooks then they won't be called again after the route changes. Instead you need to use beforeRouteUpdate or watch $route for changes.

If you want to force the component to be destroyed and recreated (not recommended) then you need to key the <router-view> on the route:

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

Read the Data Fetching guide for more information.

  • Related