vue-router动态路由实践,根据不同的用户渲染不同的菜单
in 默认分类 with 0 comment

vue-router动态路由实践,根据不同的用户渲染不同的菜单

in 默认分类 with 0 comment

vue-router-permission.jpg

静态路由配置

用户不登陆也可以查看的页面

// router index.js
export const constantRouterMap = [
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [{
      path: 'dashboard',
      component: () => import('@/views/dashboard/index'),
      name: 'Dashboard',
      meta: { title: '首页', icon: 'home', noCache: true }
    }]
  },
  {
    path: '/404', component: Layout, hidden: true,
    children: [{
      path: '',
      component: () => import('@/views/404')
    }]
  },
  {
    path: '/login',
    // component: Layout,
    hidden: true,
    name: 'login',
    component: () => import('@/views/login/index')
  }
]
export const createRouter = () => new Router({
  // mode: 'history',
  routes: constantRouterMap
})
// 重置上一次的matcher,用户退出后不刷新页面,重置router里的routes
const router = createRouter()
export default router

Vuex设置

由于this.$options.routes非响应式,因此我们需要将所有的路由放到vuex中,动态渲染菜单

路由放入state中


state: {
    routes: constantRouterMap, // 静态路由 router index.js
    addRoutes: [] // 动态匹配的路由
  }

在action中过滤路由

// 生成路由
    generatorRoutes({ commit }, roles) {
      return new Promise((resolve, reject) => {
        addRoutes = asyncRoutes.filter(route => roles.find(item => item === route.role))
        commit('SET_ROUTES', addRoutes) // 提交处理好的路由放到state中
        resolve(addRoutes)
      })

生成动态路由

当前用户可以查看的页面


router.beforeEach((to, from, next) => {
   //  获取cookie中的token
  const hasRole = getRole()
  if (hasRole && hasRole !== 'undefined') {
  // 当vuex中没有路由时,开始生成路由
    if (!store.getters.addRoutes.length) {
      // 获取当前用户可以查看的页面role
      store.dispatch('getUserRole', JSON.parse(hasRole)).then(res => {
        if (res.length) {
          // generator Routes
          store.dispatch('generatorRoutes', res).then(addRoutes => {
            // 清除上一次保存的路由
            router.matcher = createRouter().matcher
            // 通过 addRoutes添加过滤好的路由
            router.addRoutes(addRoutes.concat([{ path: '*', redirect: '/404', hidden: true }]))
            next({ ...to, replace: true })
          })
        } else {
          // if response is empty jump to login router
          removeCookies()
          next({ path: '/login' })
        }
      }).catch(() => {
        removeCookies()
        next({ path: '/login' })
      })
    } else {
      if (whiteList.indexOf(to.path) > -1) {
        next('/dashboard')
      } else {
        next()
      }
    }
  } else {
    removeCookies()
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next({ path: '/login' })
    }
  }
})
Responses