AnandShiva
AnandShiva

Reputation: 1339

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

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.

Upvotes: 3

Views: 2564

Answers (2)

Bruno Francisco
Bruno Francisco

Reputation: 4220

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

Upvotes: 3

Mirek Simek
Mirek Simek

Reputation: 86

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

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

Upvotes: 2

Related Questions