vue 动态设置路由权限

915

之前看到网上有些动态设置路由的,但是跟目前的项目不是很匹配,就自己动手实现了一种。主要思路就是:
1.配置路由的时候绑定好id,可后端开发完成后,与后端同步id就行,这id唯一不变,根据此id可找到路由地址及icon。

const routerArr = [
  {
    path: '',
    name: '',
    component: () => import( /* webpackChunkName: "strategiesMaintain" */ '@/components/Layout/Index'),
    meta: {
      requireAuth: true,
      id: 1,
      icon: 'iconzhanghuguanli',
      title: '路由1'
    },
    children: [{ 
      path: '/verificationLog',
      name: 'VerificationLog',
      component: () => import( /* webpackChunkName: "verificationLog" */ '@/views/auditManage/verificationLog'),
      meta: {
        requireAuth: true,
        id: 101,
        icon: 'icon-disanfangyanzhengrizhi',
        title: '路由11'
      }
    }, {
      path: '/systemLog',
      name: 'SystemLog',
      component: () => import( /* webpackChunkName: "systemLog" */ '@/views/auditManage/systemLog'),
      meta: {
        requireAuth: true,
        id: 102,
        icon: 'icon-xitongcaozuorizhi',
        title: '路由12'
      }
    }]
  }
];

export default routerArr;

2.设置本地路由与后端传来的路由的联系,主要是根据id绑定路由地址及iconClass

import routerModules from "@/router/modules";
import {http} from '@/utils/http'
import store from '@/store';
import { Message } from 'element-ui'

const formateResData = (val) =>{ // 格式化路由数据
  const obj = {};
  const fn = (arr)=>{
      for(let i = 0,item;item = arr[i++];){
        obj[item['meta']['id']] = {
          path: item['path'],
          iconClass: item['meta']['icon']
        };
        if(item.children && item.children.length > 0){
          fn(item.children);
        }
      }
  }
  fn(val);
  return obj;
};

const MAPOBJ  = formateResData(routerModules);
const dealWithData =  (navData) => { // 处理菜单数据
  let firstLink = "";
  const navIdArr = [];
  const fn = (arr) => {
      for (let i = 0,item;item = arr[i++];) {
        item['iconClass'] = MAPOBJ[item.id].iconClass;
        item['linkAction'] = MAPOBJ[item.id].path;
        navIdArr.push(item.id);
        if (!firstLink && !item.subMenu) { // 设置默认跳转
          firstLink = item['linkAction'];
        }
        if (item.subMenu && item.subMenu.length > 0) {
          fn(item.subMenu);
        }
      }
  }
  fn(navData);
  return {navData,navIdArr,firstLink};
};

let navIds = [];

const getNav = async (to={},from={},next=()=>{})=>{ // 获取导航数据
  const  {code,data} =  await http("/menu/list", {}, "GET"); // 获取菜单数据
  // const data = require("@/mock/api/menuData"); // 使用mock数据
  const {navData,navIdArr,firstLink} = dealWithData(data);
  store.commit('setNavData', navData);
  navIds = navIdArr;
  if(to.fullPath == '/index'){ // 从登录过来 或者是回首页
    next(firstLink);
  }else { // 刷新
    if(navIds.indexOf(to.meta.id) == -1){ // 后端没有返回该菜单
      Message.error('菜单不存在或者没有权限');
      return;
    }
    next();
  }
}

export const setGuard = (to={},from={},next=()=>{}) =>{ // 设置权限
  if(navIds.length === 0){ // 还没有获取菜单数据
    getNav(to,from,next);
  }else { // 获取到菜单数据
    if(navIds.indexOf(to.meta.id) == -1){ // 后端没有返回该菜单
      Message.error('菜单不存在或者没有权限');
      return;
    }
    next();
  }
}

3.在mainjs中引入配置

router.beforeEach((to, from, next) => {
  let token = wlhStorage.get("authorization");
  if (to.path == "/login") {
    storage.clear();// 清空缓存
    next();
  } else {
    if (to.meta.requireAuth && token) { // 登陆
      setGuard(to,from,next);
    } else { // 没有登录
      next("/login");
    }
  }
})