'Vue2 - change the route based on store value

I am trying to change the route of my components based on a value saved within the vuex store. There are four different template files, saved within different directories (template1, template2 etc). I am pulling the template id from the details store and depending on this value would like to render the component from the correct directory.

For example, if the template value in the store is 2 then load all the template2/profile component, if it is three load the template3/profile component.

import VueRouter from 'vue-router'
import store from '../store';


Vue.use(VueRouter)

const setComponent = componentName => {
    return () => import(`../template${store.getters['detailsStore/getTemplate']}/views/${componentName}`)
}

const routes = [
    {
        path: '/',
        redirect: '/details'
    },
    {
        path: '/profile',
        name: 'Profile',
        //component: () => import('../template2/views/Profile') // - this is how i was importing the component but couldn't access vuex store
        component: () => setComponent('Profile'),
    },
    {
        path: '/details',
        name: 'Details',
        component: () => setComponent('Details'),
    }
];

const router = new VueRouter({
  mode: 'history',
  routes
})

export default router

I thought creating the setComponent function would help,. but i just get a blank page. Any help would be much appreciated



Solution 1:[1]

Vue2:

Your component is not done loading. This will do it:

const asyncComp = async (componentName) => {
  const component = await import(`../template${store.getters['detailsStore/getTemplate']}/views/${componentName}`)
  return component;
};


{
  path: '/profile',
  name: 'Profile',
  component: () => asyncComp('Profile'),
}

Vue 3 solution: Here you will have defineAsyncComponent() available https://vuejs.org/api/general.html#defineasynccomponent

const asyncComp = (compName) => defineAsyncComponent(() => import(`../template${store.getters['detailsStore/getTemplate']}/views/${compName}`);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 daniel