Re-evaluate dynamic import on vue-route change

Viewed 423

I am making an admin panel that is used to manage several websites. My vue-router routes are all prefixed with the website slug and I have a beforeEach on the router that sets the website_slug in the vuex state accordingly.

Each site will use most of the same components, but there will also be several sites that have custom page components.

For this case I have made a function called importOrDefault like this:

const importOrDefault = (componentName, store) => {
    return import(/* webpackChunkName: "[request]" */ `./Pages/${store.getters.website.slug}/${componentName}`)
        .catch(() => import(/* webpackChunkName: "[request]" */ `./Pages/_shared/${componentName}`));
};

Which I use in my router config like this:

{
    path: '/:website_slug/',
    name: 'dashboard',
    component: () => importOrDefault('Dashboard', store)
}

This setup works great on load. However, when I navigate to another :website_slug, the component is not re-evaluated and the same component as the previous site is loaded. The state has changed though, so this is not the problem.

Is there a way that I can make the router component re-evaluate the function or am I missing some obvious functionality I can use for this?

2 Answers

Vue Router tries to reuse components as much as it can. Have you tried adding beforeRouteUpdate to your component to explicitly set the data (vs using mounted or something else)? You can also set the key property of the component to something explicit (like the website_slug value) to ensure the component isn't reused.

I personally prefer using key when I can.

See: https://github.com/vuejs/vue-router/issues/1490

beforeRouteUpdate method: https://jsfiddle.net/Linusborg/L7hscd8h/2208/

key method: https://jsfiddle.net/Linusborg/L7hscd8h/1528/

I have tried several solutions, but couldn't get the route component to re-evaluate. Eventually, I loaded the available websites before bootstrapping Vue and generated all possible routes for all websites.

This way, the same page for another website is a unique route and the component is evaluated for every website.

Related