vue动态添加路由之避坑指南:https://www.it610.com/article/1517505460574420992.htm
你是否遇到了:
- addRouter后出现白屏
- 路由守卫出现死循环
踩了很多坑之后,我终于悟到了vue动态添加路由的正确打开方式;
为了设计权限,在前端我们通常采取两种方式
1、在用户登录时获取该用户权限下的路由表,动态生成路由和菜单栏(后端给定路由)
2、在用户登录时获取用户权限,根据权限筛选出需要的路由(前端通过权限筛选路由)
本篇文章采用方式一
关键点:
- 使用route中addRouter方法动态添加路由
- 将路由分为
(1)动态路由 myRouterObj (可从后端获取)
(2) 静态路由 staticRoutes 没有权限也可以访问的路由
注:rootRouter 用来组装动态路由。
router index.js页面
import Vue from 'vue'
import Router from 'vue-router' import home from '@/pages/Home' import store from '../store/store' Vue.use(Router) // 动态路由 模拟后端数据 const myRouterObj = [ { path: '/dashboard', name: "dashboard", meta: { title: '系统首页' }, component: "Dashboard" }, { path: '/table', name: "commonTable", meta: { title: '表格' }, component: "CommonTable" }, { path: '/calendar', name: "calendar", meta: { title: '日历' }, component: "Calendar" } ] // 静态路由 没有权限也可以访问的路由 export const staticRoutes = [ { path: "/login", name: "login", component: () => import( "@/pages/Login.vue" ), } ]; // 根路由 const rootRouter = { path: '/', name: 'home', component: home, redirect: '/dashboard', children: [] }; export const generatorDynamicRouter = () => { return new Promise((resolve, reject) => { // myRouterObj 这里直接写在页面中了,实际应用中我们需要进行ajax请求获取 const routesForHis = generatorForHis(myRouterObj); // routesForHis .push(notFoundRouter); // 可以定义404nofoun单页面路由 rootRouter.children = routesForHis; resolve(rootRouter); }); }; export const generatorForHis = (routeMap) => { return routeMap .map(item => { const currentRouter = { path: item.path, // 路由名称,建议唯一 name: item.name, // meta: 页面标题, 菜单图标, 页面权限(供指令权限用,可去掉) meta: item.meta, // 该路由对应页面的 组件 (动态加载 @/pages/ 下面的路径文件) component: () => import(`@/pages/` + item.component + '.vue') }; // 子菜单,递归处理 if (item.children && item.children.length > 0) { currentRouter.children = generatorForHis(item.con); if (currentRouter.children === undefined || currentRouter.children.length <= 0) { delete currentRouter.children; } } return currentRouter; }) .filter(item => item); }; // 开始创建路由时 const router = new Router