Skip to content
Advertisement

Conditional route for children routes in VueJS

I wonder how to redirect a children route conditionally. I’ve tried many ways but none of them works.

I’m using a state from the store as the condition to redirect the children routes. I’ve exported my store from the file it is in and import it in the routes.js:

import store from ‘@/store’

Here is the code to handle the routes:

{
path: '/import',
component: Layout,
redirect: '/import/table',
name: 'Import',
meta: { title: 'Import', icon: 'el-icon-right' },
children: [
  {
    path: 'tree',
    name: 'Tree',
    component: () => 
    import('@/views/tree/import'),  
    beforeEach: (to,from,next) => {
      //store.state.userRole = 'Admin' redirect the route, otherwise not redirect. 
      if(store.state.userRole = 'Admin') {
        next();
      }
      else {
        next(false);
      }
      meta: { title: 'Create form', icon: 'el-icon-circle-plus-outline' },
    },

    {
    path: 'table',
    name: 'Table',
    component: () => import('@/views/table/importList'),
    meta: { title: 'List', icon: 'el-icon-document' },
    },
  ]
}

Advertisement

Answer

The proper name of the per-route guard is beforeEnter – not beforeEach. https://router.vuejs.org/guide/advanced/navigation-guards.html#per-route-guard

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement