年初了,抱着试试水的心态出去面试了两家公司;其中一家公司面试的时候多次问到了vue-router的动态路由实现权限管理的问题;回来后我就仔细研究了一下

router.addRoutes

动态路由是基于vue-router 新增的router.addRoutes方法来实现的;也就是为了达到当用户登录之后通过判断用的权限来觉得前端哪些页面能展示,哪些不能展示;

第一步 创建vue-router

router/index.js内容

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import demo from '@/components/role'
import  notFind from '@/components/404'
Vue.use(Router);
//不需要权限的路由
export const constantRouterMap = [
  {
    path: '/',
    component: HelloWorld,
    name: '首页'
  }, {
    path : '/404',
   component:notFind,
    meta : {
      title : '404未找到',
    }
  }
]
//实例化vue的时候只挂载constantRouter
export default new Router({
  routes: constantRouterMap
});

//异步挂载的路由
//动态需要根据权限加载的路由表
export const asyncRouterMap = [
  {
    path: '/role',
    component: demo,
    name: '权限测试',
    meta: { role: ['admin','super_editor'] }, //页面需要的权限
  },{
    path : '*',
    redirect : '/404'
  }
];
第二步 在入口函数中判断用户权限并添加路由
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import { asyncRouterMap, constantRouterMap } from './router';
import Vuex from "Vuex"
import VueDND from 'awe-dnd'
import BaiduMap from 'vue-baidu-map'
Vue.use(Vuex)
function hasPermission(roles, route) {
  if (route.meta && route.meta.role) {
    console.log(roles);
    return roles.some(role => route.meta.role.indexOf(role) >= 0)
  } else {
    return true
  }
}
const store = new Vuex.Store({
  state: {
    count: 0,
    token:"asdsd",
    roles:"",
    routers:[],
    addRouters:[]
  },
  getters:{
    token(){
      return "asdsd"
    },
    roles(state ){
      return state.roles
    },
    addRouters(state){
      return state.addRouters
    },
    routers(state){
      return state.routers
    }
  },
  actions:{
    GetInfo({state}){
      return {
        data:{
          role:state.roles=["admin"]
        }
      }
    },
    GenerateRoutes({ commit }, data){
      return new Promise(resolve => {
        const { roles } = data;
        console.log(asyncRouterMap,roles);
        const accessedRouters = asyncRouterMap.filter(v => {
          if (roles.indexOf('admin') >= 0) return true;
          if (hasPermission(roles, v)) {
            if (v.children && v.children.length > 0) {
              v.children = v.children.filter(child => {
                if (hasPermission(roles, child)) {
                  return child
                }
                return false;
              });
              return v
            } else {
              return v
            }
          }
          return false;
        });
        console.log(accessedRouters);
        commit('SET_ROUTERS', accessedRouters);
        resolve();
      })
    }
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      console.log(routers);
      state.addRouters = routers;
      state.routers = constantRouterMap.concat(routers);
    }
  }
});
router.beforeEach((to, from, next) => {
  if (store.getters.token) { // 判断是否有token
    if (to.path === '/login') {
      next({ path: '/' });
    } else {
      if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(res => { // 拉取info
          const roles = res.data.role;
          store.dispatch('GenerateRoutes', { roles }).then(() => { // 生成可访问的路由表
            console.log(store.getters.addRouters);
            router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          })
        }).catch(err => {
          console.log(err);
        });
      } else {
        next() //当有用户权限的时候,说明所有可访问路由已生成 如访问没权限的全面会自动进入404页面
      }
    }
  } else {
    next('/login'); // 否则全部重定向到登录页
  }
});

这样的话,就算用户权限不够,也不会看到那些页面的静态资源;而是直接显示自己编辑的404页面

Logo

前往低代码交流专区

更多推荐