美文网首页
Vue动态添加路由

Vue动态添加路由

作者: Enginner_XZ | 来源:发表于2020-10-20 16:11 被阅读0次
    • 开发一个不同用户不同权限显示不同菜单项目 , 需要实现不同权限添加不同路由
    • 通过前置路由守卫router.beforeEach实现
    • 二级菜单路由列表
    
    const childRouters = {
      "/good": {
        path: "/good",
        name: "Good",
        component: () =>
          import(/* webpackChunkName: "good" */ "../views/Good/Good.vue"),
      },
      "/category": {
        path: "/category",
        name: "Category",
        component: () =>
          import(
            /* webpackChunkName: "category" */ "../views/Category/Category.vue"
          ),
      },
      "/brand": {
        path: "/brand",
        name: "Brand",
        component: () =>
          import(/* webpackChunkName: "brand" */ "../views/Brand/Brand.vue"),
      },
      "/attribute": {
        path: "/attribute",
        name: "Attribute",
        component: () =>
          import(
            /* webpackChunkName: "attribute" */ "../views/Attribute/Attribute.vue"
          ),
      },
      "/order": {
        path: "/order",
        name: "Order",
        component: () =>
          import(/* webpackChunkName: "order" */ "../views/Order/Order.vue"),
      },
      "/topic": {
        path: "/topic",
        name: "Topic",
        component: () =>
          import(/* webpackChunkName: "topic" */ "../views/Topic/Topic.vue"),
      },
      "/statdata": {
        path: "/statdata",
        name: "Statdata",
        component: () =>
          import(
            /* webpackChunkName: "statdata" */ "../views/Statdata/Statdata.vue"
          ),
      },
    };
    
    • 封装重复代码
    const genRoute = () => {
      let newRouters = [];
      for (let i = 0; i < store.state.powerList.length; i++) {
        var path = store.state.powerList[i].path;
        if (childRouters[path]) {
          newRouters.push(childRouters[path]);
        }
      }
      router.addRoutes([
        {
          path : '/home',
          component:() => import(/* webpackChunkName: "home" */ '../views/Home/Home.vue'),
          children : newRouters
        }
      ])
    };
    
    • 前置路由守卫
    router.beforeEach((to, form, next) => {
      // 当没有本地token , 并且目标路由不是login时执行
      if (to.path !== "/login" && !localStorage.getItem("token")) {
        return next("/login");
        // 当有token 没有数据时执行
      } else if (store.state.powerList.length === 0 && localStorage.getItem("token")) {
        GetUserByToken().then((response) => {
          store.commit("savePowerList", response.data.menu );
          genRoute();
          return next( store.state.powerList[0].path );
        });
      } else {
        next();
      }
    });
    

    相关文章

      网友评论

          本文标题:Vue动态添加路由

          本文链接:https://www.haomeiwen.com/subject/wnudmktx.html