網(wǎng)站開發(fā)需要的編程軟件杭州百度快速排名提升
之前有人問我 ,如果是二級(jí)路由如何添加,這里我做一個(gè)補(bǔ)充吧。直接拿方法去用就行。也不做解釋了。稍微看下就能看懂了
假設(shè),后端返回給我們一個(gè)數(shù)據(jù) [“/defa”,"/defa/defa1"] 這樣的一個(gè)路由表,我們就需要通過這個(gè)路由表去篩選匹配我們的動(dòng)態(tài)路由,然后在進(jìn)行添加。假設(shè)我們的動(dòng)態(tài)路由是
[{path: "/defa",name: "defa",component: () => import("@/views/DefaCat.vue"),children: [{path: "/defa/fase1",name: "homelist1",component: () => import("@/views/UserZi.vue"),},{path: "/defa/fase9",name: "homelist9",component: () => import("@/views/UserZi.vue"),},],},{path: "/defa/fase2",name: "homelist2",component: () => import("@/views/UserZi.vue"),},
];
這樣的一組數(shù)據(jù),按照后端返回給我們的數(shù)據(jù)表,我們最終要拿到的數(shù)據(jù)是。
[{path: "/defa",name: "defa",component: () => import("@/views/DefaCat.vue"),children: [{path: "/defa/fase1",name: "homelist1",component: () => import("@/views/UserZi.vue"),},],},
];
這樣才符合我們的設(shè)計(jì)需要,所以這里添加了一個(gè)方法,能夠篩選出符合我們的代碼,注意,這有2個(gè)弊端,第一,是當(dāng)你父路由不存在后端的路由表而子路由存在時(shí),子路由照樣會(huì)被剔除掉,第二解釋,只能篩選2層,也就是說動(dòng)態(tài)路由里只有父路由子路由,多的無法篩選了。
const filterRoutes = (targetPaths:any, sourceRoutes:any) => {return sourceRoutes.map((route:any) => {const filteredChildren = route.children? route.children.filter((child:any) => targetPaths.includes(child.path)): [];return {...route,children: filteredChildren,};}).filter((route:any) => route.children.length > 0 || targetPaths.includes(route.path));
};
函數(shù)接收2個(gè)參數(shù),第一個(gè)參數(shù)是后端傳給我的路由表[“/defa”,"/defa/defa1"] ,第二個(gè)參數(shù)就是前端定義的整個(gè)的動(dòng)態(tài)路由,函數(shù)的返回值就是我們的數(shù)據(jù)啦。我們可以根據(jù)這個(gè)數(shù)據(jù)動(dòng)態(tài)添加路由或者是導(dǎo)航欄的權(quán)限控制
簡易版的動(dòng)態(tài)添加路由,可以作為參考,這里沒有加入token是否存在的邏輯。
router.beforeEach((to, from, next) => {console.log(to.name, 99);if (!to.name) {filterRoutes(arrlist,routerlist).map((item: any) => {router.addRoute(item); });next({ ...to, replace: true });} else {next();}next();
});
現(xiàn)在來說應(yīng)該算是完全好了,這個(gè)這個(gè)權(quán)限組件,這里我們前端做的事情太多了,可以把活適當(dāng)?shù)姆忠稽c(diǎn)給后端,讓后端傳我們能直接用的路由表,不是更爽嗎 哈哈。
我看哪天有時(shí)間,我會(huì)出一版封裝好的有權(quán)限管理的vue3框架,包括路由權(quán)限和導(dǎo)航欄權(quán)限都會(huì)封裝好,開箱即用。