根据不同的权限动态加载路由

275 阅读1分钟

这种操作的目的是为了防止没权限的页面也能通过输入url进入。 需要判断权限的路由放在一个数组里:

  {
    path: "/playback",
    name: "playback",
    component: PlayBack,
    //路由中的meta项可以携带自己设置的值
    meta: {
      roles: 5
    }
  },
 ]

其余的默认路由

  path: "/",
  name: "index",
  component: Index,
  redirect: "/realplay",
  children: [
    {
      path: "/realplay",
      name: "realplay",
      component: RealPlay,
      meta: {
        keepAlive: false
      }
    },]}

导出路由数组

export { arr, routeHome };

login文件里导入路由数组以便做判断

import { arr, routeHome } from "../router/index";

//登录成功后调用权限接口,拿到返回值处理路由数组(axios)

axios.post("Api/User/GetUserUIModule").then((items) => {
        //遍历路由数组通过权限弄新的路由
        arr.forEach((t: any) => {
          items.data.message.forEach((item: any) => {
            if (t.meta.roles == item.modelid) {
              routeHome.children.push(t);
            }
          });
});

利用addRoutes向总的路由里添加拼接好的新路由数组

this.$router.addRoutes([routeHome]);

存在浏览器内存里防止刷新之后路由丢失(好像没作用),这种方法被弃用了,忘记为啥了

//window.sessionStorage.setItem("routes",JSON.stringify(routeHome));
// let a = window.sessionStorage.getItem("routes");
// if (a) {
	// this.$router.addRoutes([JSON.parse(a)]);
// } else 处理路由逻辑

在最外面的文件(index.vue或app.vue)created里写上处理路由的逻辑(每次刷新后防止页面空白)。就可以了