Vue动态路由实现逻辑
1、登录后跳转的授权页redierect.vue,获取动态路由的数组,存储于store.ts
2、在main.ts 中引用路由守卫文件
import "./router/permission";
3、在permission.ts中用到了
router.beforeEach
导航前置守卫,在调用路由之前会先调用该方法,在该方法中通过store.ts的路由数组动态渲染路由后访问。
4、在asyncRouter.js通过定义 getAsyncRoutes 进行路由数组的格式化,同时此处也可以用来通过接口获取路由信息,但是我就不查了,太浪费资源。
permission.ts内容如下// 进度条引入设置如上面第一种描述一样 import router from "@/router/index" import store from "@/store/index" import api from "@/api/index" // import { getToken } from "@/utils/auth" // get token from cookie import { getAsyncRoutes } from "@/utils/asyncRouter" const whiteList = ["/login","","/redirect"]; router.beforeEach( async (to, from, next) => { // NProgress.start() // document.title = to.meta.title; // 获取用户token,用来判断当前用户是否登录 const hasToken = true; if (hasToken) { //白名单直接进入 if (whiteList.indexOf(to.path) >0) { next() //next({ path: "/" }) // NProgress.done() } else { //异步获取store中的路由 const route= store.getroutestatus() ; const hasRouters = route!="null" && route!=null && route!="1" //判断store中是否有路由,若有,进行下一步 if (route!=null && route=="1" ) { console.log(router.options); next() } else { //store中没有路由,则需要获取获取异步路由,并进行格式化处理 //author:lxfamn date:20210117 descrip: //这里没没有异步获取路由,而是从本地存储中直接获取,因为路由数组已在登录时获取完成 try { console.log("路由守卫"); const accessRoutes = getAsyncRoutes(await store.get_routes() ); // 动态添加格式化过的路由 if (accessRoutes.length) { accessRoutes.forEach(item => { router.addRoute("Home",item) }) } store.setroutestatus(1) console.log(to.path) // console.log(router.options); // console.log(router.getRoutes()); // console.log(router.hasRoute("abc")) // console.log(router.hasRoute("About")) // router.addRoute(accessRoutes); next({ ...to, replace: true }) } catch (error) { // Message.error("出错了") next(`/login?redirect=${to.path}`) } } } } else { if (whiteList.indexOf(to.path) !== -1) { next() } else { next(`/login?redirect=${to.path}`) } } }) router.afterEach(() => { })