Force Don't reuse same component instance for Dynamic routes, vue-router

2k Views Asked by At

I have a dynamic route with vue-router something like this,

import customReportWrapper from './customReportWrapper.vue';

let router = new Router({
  mode: 'history',
  routes: [{
      path: '/insights/custom-reports/:id',
      name: 'custom-reports',
      page: 'insights',
      component: customReportWrapper
  }]
})

Every time someone navigates to this route, CustomReportWrapper.vue will be used to render. But they each navigation uses the same Component instance, as mentioned in the vue-router docs here.

I want to override this behavior so that every new navigation creates a new Vue component instance. If this is not supported directly any workaround also will be helpful.

2

There are 2 best solutions below

0
On

You just need to add the :key="$route.path" to your parent component.

Something like:

App.vue

<template>
  <main :key"$route.path">
    <router-view></router-view>
  </main>
</template>

Explanation

The key acts as a sort of flag that tells Vue "if the data associated with this child component is moved somewhere else, then move the component along with it to preserve the changes that already exist". Since you navigated to the same component (same route but just different :id) you want to re-render the component. Be careful with this approach though: it re-renders all the components and sub components

0
On

The template has a typo, :key="$route.path", not $router:

<template>
  <main :key="$route.path">
    <router-view></router-view>
  </main>
</template>