289  
查询码:00000566
使用管理中心进行动态路由配置
作者: 陈婉 于 2020年06月17日 发布在分类 / 人防组 / 人防前端 下,并于 2020年06月17日 编辑
vue 动态路由 管理中心

管理中心动态路由配置

严格按照静态路由的结构进行配置(至少包含两级,path路径等信息)

粘贴图片

参照静态路由信息配置动态路由数据

粘贴图片

注意 事项:


  • 首页
  • 一级菜单实际指向不必填写
  • 菜单名称和菜单标题一致
  • 是否显示选是
  • 一级菜单有斜杠,二级菜单路径没有斜杠
  • 实际指向从@/后面的开始复制粘贴图片


前端页面

用户登陆进来之后,根据token获取用户信息

在router文件夹下面的index.js中

由于vue中的接口请求封装成了异步,不能满足我们的要求,所以使用原生的XMLHttpRequest

粘贴图片


//如果地址栏中有参数,处理数据存入store和session中
//没有获取store中的路由数据
if (decodeURI(location.search).indexOf("token") != -1) {
  let backInfo = GetRequest();
  store.commit("setToken", backInfo.token);
  //根据token获取用户信息
  let parameter = {
    code: backInfo.token,
    state: "1",
    tenantId: ""
  }
  let oReq = new XMLHttpRequest();
  oReq.open("POST", baseServerUrl+"api/services/app/Login_OAuth/GetUserInfoByToken", false); // 同步请求
  // oReq.open("POST", "192.168.199.203:8099/api/services/app/Login_OAuth/GetUserInfoByToken", false); // 同步请求
  oReq.setRequestHeader("Content-type", "application/json");
  oReq.setRequestHeader("access_token", store.state.user.token);
  
  oReq.send(JSON.stringify(parameter));//发送数据需要自定义,这里发送的是JSON结构
  let res = oReq.responseText;//响应结果
  let data = JSON.parse(JSON.parse(res).result).result;
  store.commit("setUserInfo", JSON.stringify(data));
  store.commit("setTenantId", data.userMsg.tenantId);
  let routers = data.rightMsg.filter(e => e.systemName == "人事管理系统")[0].menus.filter(item => item.authority == true);
  console.log(store);
  store.commit("setRouters", JSON.stringify(routers));
  getRouter();
} else {
  console.log(store.state.user.routers);
  if (store.state.user.routers) {
    getRouter();
  }else{
    window.location.href=window.g.utilitySystemUrl;
  }
}

处理路由


根据接口返回的路由信息,整理成我们需要的路由格式


//处理路由数据
const getRouter = () => {
  let routersList = JSON.parse(store.state.user.routers);
  let addRouters = [];
  console.log("routes222", routersList);
  let isHome=routersList.filter(e=>e.path==='/home');
  routersList.forEach((element, index) => {
    let children = [];
    element.sonMenus.forEach(ele => {
      if (ele.authority) {
        children.push({
          path: ele.path,
          name: ele.path,
          meta: {
            icon: `iconfont ${ele.icon}`,
            title: ele.name
          },
          component: () => import(`@/${ele.component}`)
        })
      }
    })
    addRouters.push(
      {
        path: element.path === '/home' ? '/' : element.path,
        name: element.path.substring(1),
        meta: {
          icon: `iconfont ${element.icon}`,
          title: element.name,
          hideInBread: true,
          hideInMenu: !element.isshow
        },
        component: Main,
        children: children
      }
    );
  });
  if(addRouters.length>0 && isHome.length>0){
    addRouters.filter(e=>e.path === '/')[0].redirect='/home';
  }else if(addRouters.length>0 && isHome.length==0){
    addRouters.filter(e=>e.path === '/organization_position')[0].path='/';
    addRouters.filter(e=>e.path === '/')[0].redirect='/organization_position_list';
  }
  routes.insertSome(0, addRouters);
  // store.commit("setRouterReal", CircularJSON.stringify(routes));
  console.log(routes)
}


注意事项

是否需要重定向到首页

粘贴图片

示例:

import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import Main from '@/components/main'
// import CircularJSON from 'circular-json'
import iView from 'view-design'
import { setToken, getToken, canTurnTo, setTitle } from '@/libs/util'
import config from '@/config'
// const baseServerUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro
const baseServerUrl = 'http://192.168.199.203:8099/'


Array.prototype.insertSome = function (place, thing) {
  // 向数组插入元素, place是位置(整数) thing是要插入的数据
  if (thing instanceof Array) {
    var allLen = this.length + thing.length; //合并数组后的长度
    var thingLen = thing.length; //要插入的数组长度
    var thisLen = this.length; //被插入数组的长度
    for (var i = allLen; i > place + thingLen; i--) {
      // 先把原来数组在place后面的元素移去后方;
      this[i - 1] = this[thisLen - 1];
      thisLen--;
    }
    for (var k = i - 1; k > thisLen - 1; k--) {
      // 再把要插入的数组从尾到头插入原来的数组
      this[k] = thing[thingLen - 1];
      thingLen--;
    }
  } else {
    // 如果thing不是个数组,那么用splice就行了
    this.splice(place, 0, thing);
  }
}
const { homeName } = config
//对地址栏的参数进行处理
const GetRequest = () => {
  var url = decodeURI(location.search); //获取url中"?"符后的字串
  var theRequest = new Object();
  if (url.indexOf("?") != -1) {
    var str = url.substr(1);
    var strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
  }
  return theRequest;
}
//处理路由数据
const getRouter = () => {
  let routersList = JSON.parse(store.state.user.routers);
  let addRouters = [];
  console.log("routes222", routersList);
  let isHome=routersList.filter(e=>e.path==='/home');
  routersList.forEach((element, index) => {
    let children = [];
    element.sonMenus.forEach(ele => {
      if (ele.authority) {
        children.push({
          path: ele.path,
          name: ele.path,
          meta: {
            icon: `iconfont ${ele.icon}`,
            title: ele.name
          },
          component: () => import(`@/${ele.component}`)
        })
      }
    })
    addRouters.push(
      {
        path: element.path === '/home' ? '/' : element.path,
        name: element.path.substring(1),
        meta: {
          icon: `iconfont ${element.icon}`,
          title: element.name,
          hideInBread: true,
          hideInMenu: !element.isshow
        },
        component: Main,
        children: children
      }
    );
  });
  //如果系统有首页,重定向到首页
  if(addRouters.length>0 && isHome.length>0){
    addRouters.filter(e=>e.path === '/')[0].redirect='/home';
  }else if(addRouters.length>0 && isHome.length==0){
    //没有首页重定向到需要定向的页面
    addRouters.filter(e=>e.path === '/organization_position')[0].path='/';
    addRouters.filter(e=>e.path === '/')[0].redirect='/organization_position_list';
  }
  routes.insertSome(0, addRouters);
  // store.commit("setRouterReal", CircularJSON.stringify(routes));
  console.log(routes)
}
//如果地址栏中有参数,处理数据存入store和session中
//没有获取store中的路由数据
if (decodeURI(location.search).indexOf("token") != -1) {
  let backInfo = GetRequest();
  store.commit("setToken", backInfo.token);
  //根据token获取用户信息
  let parameter = {
    code: backInfo.token,
    state: "1",
    tenantId: ""
  }
  let oReq = new XMLHttpRequest();
  oReq.open("POST", baseServerUrl+"api/services/app/Login_OAuth/GetUserInfoByToken", false); // 同步请求
  // oReq.open("POST", "192.168.199.203:8099/api/services/app/Login_OAuth/GetUserInfoByToken", false); // 同步请求
  oReq.setRequestHeader("Content-type", "application/json");
  oReq.setRequestHeader("access_token", store.state.user.token);

  oReq.send(JSON.stringify(parameter));//发送数据需要自定义,这里发送的是JSON结构
  let res = oReq.responseText;//响应结果
  let data = JSON.parse(JSON.parse(res).result).result;
  store.commit("setUserInfo", JSON.stringify(data));
  store.commit("setTenantId", data.userMsg.tenantId);
  let routers = data.rightMsg.filter(e => e.systemName == "人事管理系统")[0].menus.filter(item => item.authority == true);
  console.log(store);
  store.commit("setRouters", JSON.stringify(routers));
  getRouter();
} else {
  console.log(store.state.user.routers);
  if (store.state.user.routers) {
    getRouter();
  }else{
    window.location.href=window.g.utilitySystemUrl;
  }
}
// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(Router)
const router = new Router({
  base: '/Staff/',
  routes,
  mode: 'history'
})

const LOGIN_PAGE_NAME = 'login'
const turnTo = (to, access, next) => {
  if (canTurnTo(to.name, access, routes)) next() // 有权限,可访问
  else next({ replace: true, name: 'error_401' }) // 无权限,重定向到401页面
}
router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  const token = getToken()
  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: homeName // 跳转到homeName页
    })
  } else {
    //拉取数据字典
    console.log(store.state.dic.hasGetDic);
    if (!store.state.dic.hasGetDic) {
      let oReq = new XMLHttpRequest();
      oReq.open("get", baseServerUrl+"DataShare/api/services/app/CodeMain/GetCodeMainItems", false); // 同步请求
      oReq.setRequestHeader("Content-type", "application/json");
      oReq.setRequestHeader("access_token", store.state.user.token);
      oReq.send();//发送数据需要自定义,这里发送的是JSON结构
      let res = oReq.responseText;//响应结果
      const data = JSON.parse(res).result;
      let dicHash = new Map();

      for (let index = 0; index < data.length; index++) {
        const element = data[index];
        let codeItemList = [];
        element.codeItems.forEach(item => codeItemList.push(Object.values(item)));
        dicHash.set(element.codeName,new Map(codeItemList));
      }
      store.commit('setDic', dicHash)
      store.commit('setHasGetDic', true)
    }
    //连接SignalR
    if (!store.state.signalr.hasConnected) {
      store.dispatch('connect');
    }
  }
  next() // 跳转
})
router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})
export default router


 最新评论
当前评论数1  查看更多评论


 推荐知识

 历史版本

修改日期 修改人 备注
2020-06-17 17:31:35[当前版本] 陈婉 创建版本

 附件

附件类型

JPGJPG PNGPNG

知识分享平台 -V 4.8.7 -wcp