vue 动态添加router的实施方案 iview-admin2.0

1.下载异步加载插件

npm install  babel-plugin-syntax-dynamic-import@6.18.0 -D
或者npm install  babel-plugin-syntax-dynamic-import@6.18.0 --save--dev  //插件依赖

参考:

//.babelrc 文件夹中增加
  "plugins": [
    "syntax-dynamic-import"
  ],

iview-admin2.0中实现的:https://github.com/iview/iview-admin.git
// 动态路由函数()

export let initroute = function(arr) {
  // arr 后台返回的路由数组
  let routes = arr.map((item, index) => {
  // 整理成自己的路由格式
    return {
     // 路由路径
      path: item.webPath,
      // 路由别名
      name: item.name,
      // 携带参数
      meta: {
        icon: item.icon,
        title: item.description
      },
      // 组件
       component: Main,
       children: item.children.map((oitem, index) => {
       // 不规则路由处理
        if (oitem.component.indexOf("_c") != -1) {
         // 消除路由多余字符串
          oitem.component = oitem.component.replace("_c/cwl", "");
          return {
            path: oitem.webPath,
            name: oitem.name,
            meta: {
              icon: item.icon,
              title: oitem.description
            },
            // 动态路由增加 (webpack 不能完全动态增加路径 因此只能使用拼接路径 坑拼接2个文件夹 不然那报错)
            component: () => import(`_c/cwl${oitem.component}`)
          };
        }
       })
    };
  });
  return routes;
};

实现思路
1.登录是将路由添加到路由 并缓存到本地

// route对象
import router from "@/router";
// routes 数组
import routes from "@/router/routers.js";

//方法
   handleSubmit({ userName, password }) {
      password = md5(password);
      this.handleLogin({ userName, password }).then((res) => {
        if (!res.success) {
          // 登录
          this.message = res.respDesc;
        } else {
         this.getUserInfo().then((res) => {
            // this.$router.push({
            //   name: this.$config.homeName,
            // });
            //添加路由
            this.addrout().then((response) => {
              // 路由数据
             sessionStorage.setItem("routelist", response.respBody);
              let routingArray = initroute(JSON.parse(response.respBody));
               routes.push(...routingArray);
              router.addRoutes(routes);
              this.$router.push({
                name: this.$config.homeName,
              });
              // this.getUserInfo().then((res) => {
              //   console.log(res, "===123");
              //   this.$router.push({
              //     name: this.$config.homeName,
              //   });
              // });
            });
          });
        }
      });
    },

2.路由刷新 取出缓存 在router.beforeEach中添加

import { initroute } from "@/libs/initroute";
//取出缓存
let routelist =sessionStorage.getItem("routelist");
// 判断缓存是否有 是否已经添加过
if(routelist&&routes.length<6){
  let routelist = sessionStorage.getItem("routelist");
  let routingArray = initroute(JSON.parse(routelist));
  routes.push(...routingArray);
  router.addRoutes(routes);
}
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 {
    if (store.state.user.hasGetInfo) {
      turnTo(to, store.state.user.access, next);
      console.log(to, "====456");
    } else {
      store
        .dispatch("getUserInfo")
        .then(user => {
          // 拉取用户信息,通过用户权限和跳转的页面的name来判断是否有权限访问;access必须是一个数组,如:['super_admin'] ['super_admin', 'admin']
          turnTo(to, user.access, next);
          console.log(to, "====123");
        })
         .catch(() => {
          setToken("");
          next({
            name: "login"
          });
        });
    }
  }
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

web修理工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值