基于 vue-admin-template的动态路由
1. 拆分静态路由与动态路由
静态路由----所有人都可以访问—首页/登录/404
动态路由–有权限的人才可以访问—组织/角色/员工/权限
2. 根据用户权限添加动态路由
- 获取对应的权限标识(vuex中actions中把用户资料通过return
进行返回,在页面鉴权中调用获取用户资料得方法时候可以获取到用户资料) - 筛选出动态路由
- 添加到当前路由表
- vuex的actons中把用户资料返回—拿权限标识
const actions = {// user loginasync loginFn(context, data) {const res = await login(data)context.commit('setUserToken', res.data)},async getUserInfo(context) {const res = await getUserInfo()console.log(res.data, 'UserInfo')// 把用户资料存储到vuexcontext.commit('setUserInfo', res.data)// 把用户资料返回 进行筛选return res.data},logout(context) {context.commit('removeUserToken')context.commit('setUserInfo', {})}
}
- perssion.js 页面鉴权中,拿到权限标识去和所有的动态路由对象进行筛选匹配
- 筛选 动态添加路由
- 把路由信息存储到vuex
router.beforeEach(async(to, from, next) => {NProgress.start()// 有tokenif (store.getters.token) {if (to.path === '/login') {next('/dashboard')NProgress.done()} else {if (!store.getters.userId) {const { roles } = await store.dispatch('user/getUserInfo')// 用户标识 和 所有路由模块的name 筛选 匹配// 拿到用户标识 roles 拿到所有的路由模块 asyncRoutes// console.log(roles, 'roles')// 筛选 动态路由 通过addRoutes动态添加到路由表李const filterRoutes = asyncRoutes.filter(item => {console.log(item, 'item')return roles.menus.includes(item.name)})// 提交mutations,把筛选的动态路由存储到state中store.commit('user/setRoutes', filterRoutes)// console.log(filterRoutes, 'filterRoutes')// 动态添加到路由表router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])}next()}} else { // 没有tokenif (whiteList.includes(to.path)) {next()} else {next('/login')NProgress.done()}}
})
- vuex
const getDefaultState = () => {return {token: getToken(),userInfo: {},routes: constantRoutes // 静态路由数组}
}const state = getDefaultState()const mutations = {setUserToken(state, token) {state.token = tokensetToken(token)},removeUserToken(state) {state.token = ''removeToken()},setUserInfo(state, userInfo) {state.userInfo = userInfo},setRoutes(state, newRoutes) {state.routes = [...constantRoutes, ...newRoutes] // 静态路由+动态路由}
}
- 左侧菜单页面的数据要从vuex中读取
layout/components/Sidebar/index.vue
3. 退出登录重置路由
import { constantRoutes, resetRouter } from '@/router'
logout(context) {// 删除tokencontext.commit('removeUserToken')// 删除用户资料context.commit('setUserInfo', {})// 重置路由resetRouter()}