Vue中如何實(shí)現(xiàn)動(dòng)態(tài)路由的示例代碼
目錄
- 前言
- 實(shí)現(xiàn)效果
- 使用的技術(shù)棧
- 實(shí)現(xiàn)思路
- 具體實(shí)現(xiàn)
- 首先我們來設(shè)計(jì)數(shù)據(jù)
- 封裝一下axios函數(shù)
- 使用vuex實(shí)現(xiàn)全局?jǐn)?shù)據(jù)共享
- 將數(shù)據(jù)轉(zhuǎn)化為樹形化結(jié)構(gòu)
- 基礎(chǔ)路由模塊
- 實(shí)現(xiàn)動(dòng)態(tài)路由
- 在main.js中配置路由守衛(wèi)
- 總結(jié)
前言
我們?cè)陧?xiàng)目開發(fā)的過程中,難免會(huì)使用路由,那么我們?cè)陂_發(fā)多角色的時(shí),由于每個(gè)角色的權(quán)限不同,因此訪問到的頁面肯定也要有所限制,這個(gè)時(shí)候我們就需要使用動(dòng)態(tài)路由
實(shí)現(xiàn)效果
使用的技術(shù)棧
- 使用了koa2來作為后端
- 使用vuex實(shí)現(xiàn)全局的數(shù)據(jù)共享
- vue3的語法
- 當(dāng)然這里面還會(huì)使用一些算法(遞歸算法)
首先使用 vue create project-name 創(chuàng)建項(xiàng)目
后端使用koa2 項(xiàng)目名稱 從創(chuàng)建項(xiàng)目
實(shí)現(xiàn)思路
首先我們先來捋一下實(shí)現(xiàn)的思路:
- 后端需要設(shè)計(jì)數(shù)據(jù),這個(gè)數(shù)據(jù)包含路由的路徑path,id ,pid(該路由的父級(jí)路由id),title 這里面是要顯示的內(nèi)容
- 同樣我們?cè)谇岸丝梢阅M登錄,創(chuàng)建幾個(gè)用戶,然后我們給用戶設(shè)計(jì)的字段可以是這樣的 id(用戶id),name(用戶姓名)
- auth(權(quán)限設(shè)置,是一個(gè)數(shù)組,表明可以訪問的路由的id)
- 前端通過axios來訪問后端的數(shù)據(jù),然后獲取數(shù)據(jù)之后前端將其樹形化(使用遞歸算法),然后我們可以將其轉(zhuǎn)換為動(dòng)態(tài)的路由結(jié)構(gòu)(這部分可以封裝一個(gè)工具函數(shù)來實(shí)現(xiàn))
- 我們可以借助vuex來實(shí)現(xiàn)axios的異步請(qǐng)求,通過mutations來將值賦值給state中定義的數(shù)據(jù)。這樣我們就可以實(shí)現(xiàn)全局的數(shù)據(jù)共享。
具體實(shí)現(xiàn)
首先我們來設(shè)計(jì)數(shù)據(jù)
這部分是路由菜單
module.exports = [ { ? id: 1, ? pid: 0, //pid為0表明為頂層 ? path: "/course", ? name: "Course", ? title: "課程管理", }, { ? id: 2, ? pid: 1, ? path: "operate", ? name: "CourseOperate", ? Link: "course/operate", ? title: "課程操作", }, { ? id: 5, ? pid: 0, ? path: "/student", ? name: "Student", ? title: "學(xué)生管理", }, { ? id: 6, ? pid: 5, ? path: "operate", ? name: "StudentOperate", ? Link: "/student/operater", ? title: "學(xué)生操作", }, ...];?
當(dāng)然這里面我只展示部分?jǐn)?shù)據(jù),其實(shí)可以依次類推,我們不難發(fā)現(xiàn),pid是父級(jí)路由的id,這樣做就是為了后期將數(shù)據(jù)加工成樹形結(jié)構(gòu)。
用戶的數(shù)據(jù):
module.exports = [ { ? id: 1, ? name: "張三", ? auth: [1, 2, 5, 6], }, { ? id: 2, ? name: "李四", ? auth: [1, 2, 4, 5, 6, 7], }, { ? id: 3, ? name: "王五", ? auth: [1, 2, 3, 4, 5, 6, 7], },];?
正如我們之前所說,這個(gè)用戶id包含這幾個(gè)字段,其中auth這個(gè)字段無疑是最重要的,他是一個(gè)數(shù)組,里面存的時(shí)路由的id,表明為用戶的訪問權(quán)限。
封裝一下axios函數(shù)
在這個(gè)小的項(xiàng)目里面,我們需要使用aixos函數(shù)來請(qǐng)求后端的數(shù)據(jù),那么我們和不妨封裝一個(gè)請(qǐng)求函數(shù),這樣更方便我們請(qǐng)求后端的數(shù)據(jù)
import axios from "axios";import qs from "qs";//這里面的uid是要傳入的用戶id值function getUserRouters(uid) { ?return axios({ ? ?url: "http://localhost:3000/user_router_auth", ? ?method: "post", ? ?headers: { ? ? ?"Content-Type": "application/x-www-form-urlencoded", ? }, ? ?data: qs.stringify({ uid }), }) ? .then((res) => { ? ? ?return res.data; ? }) ? .catch((err) => { ? ? ?throw err; ? });}export { getUserRouters };?
其中url是后端的接口,data代表要傳遞的數(shù)據(jù),qs.stringify表明將uid轉(zhuǎn)換為json字符串。這個(gè)封裝的函數(shù)最終會(huì)返回一個(gè)Promise.then()。
使用vuex實(shí)現(xiàn)全局?jǐn)?shù)據(jù)共享
action部分
用來做異步請(qǐng)求,獲取后端的數(shù)據(jù),并且將其進(jìn)行樹形化處理。
import { getUserRouters } from "@/service";import { toTreeList } from "@/utils/utils";export default { ?async setUserRouters({ commit, state }) { ? ?// 使用axios獲取數(shù)據(jù) ? ?const userRouters = await getUserRouters(state.uid); ? ?// 將獲取到的后端數(shù)據(jù)樹形化 ? ?const list = toTreeList(userRouters); ? ?console.log(list); ? ?commit("setAuth", true); ? ?commit("setUserRouters", list); },};??
mutations部分:
將獲取到的數(shù)據(jù)存放在state中,便于進(jìn)行全局訪問。
export default { ?// 更改權(quán)限 ?setAuth(state, Auth) { ? ?state.hasAuth = Auth; }, ?// 將數(shù)據(jù)存儲(chǔ)在state中 ?setUserRouters(state, userRouters) { ? ?state.TreeList = userRouters; },};?
state部分
export default { ?uid: 1, ?hasAuth: false, ?TreeList: [],};?
將數(shù)據(jù)轉(zhuǎn)化為樹形化結(jié)構(gòu)
function toTreeList(list, id = 0) { ?let res = []; ?list.forEach((item) => { ? ?if (item.pid === id) { ? ? ?item.children = toTreeList(list, item.id); ? ? ?// ? 這一步是為了是最里層的children會(huì)是空,應(yīng)該刪除 ? ? ?if (item.children.length == 0) delete item.children; ? ? ?res.push(item); ? } }); ?return res;}
思路:
在這個(gè)封裝函數(shù)里面使用到了遞歸的思想,我們?cè)谠O(shè)計(jì)數(shù)據(jù)的時(shí)候給每一個(gè)數(shù)據(jù)都設(shè)計(jì)了id和pid,那么最頂層元素的pid為0(沒有父級(jí)元素),其他子級(jí)都擁有pid,所以我們可以這樣操作,設(shè)計(jì)一個(gè)函數(shù),默認(rèn)傳入從后端獲取到的數(shù)據(jù)list,和最頂層元素pid值(默認(rèn)為0),然后我們對(duì)list進(jìn)行遍歷,判斷l(xiāng)ist中的元素item的pid值與id是否相等,如果相等,那么item.children=toTreeList(list,item.id)來進(jìn)行遞歸調(diào)用,這樣當(dāng)pid和id值不相同時(shí),就會(huì)執(zhí)行res.push(item)將元素push到res里面。
基礎(chǔ)路由模塊
import { createRouter, createWebHashHistory } from "vue-router";?const routes = [ { ? ?name: "home", ? ?path: "/", ? ?component: () => import("../views/Home.vue"), }, { ? ?name: "NotFound", ? ?path: "/:pathMatch(.*)*", ? ?component: () => import("../views/NotFound.vue"), },];?const router = createRouter({ ?history: createWebHashHistory(), ?routes,});?export default router;
當(dāng)輸入的路徑不存在時(shí)就會(huì)跳轉(zhuǎn)到NotFound這個(gè)組件顯示這個(gè)頁面
實(shí)現(xiàn)動(dòng)態(tài)路由
function generateRouter(userRouters) { ?let newRouters = userRouters.map((r) => { ? ?let routes = { ? ? ?path: r.path, ? ? ?name: r.name, ? ? ?component: () => import(`@/views/${r.name}`), ? }; ? ?if (r.children) { ? ? ?routes.children = generateRouter(r.children); ? } ? ?return routes; }); ?return newRouters;}
其中傳入的userRouters是經(jīng)過樹形化處理的數(shù)據(jù),同樣這里面還是需要進(jìn)行遞歸調(diào)用,這里對(duì)路由進(jìn)行了配置,包括路由的路徑,名稱,都從后端獲取。然后判斷傳入的樹形結(jié)構(gòu)數(shù)據(jù)是否含有子元素,如果有就遞歸調(diào)用給routes追加children,然后將處理過的routes返回,最后再將newRouters返回。
在main.js中配置路由守衛(wèi)
import router from "./router";import store from "./store";import { generateRouter } from "./utils/utils";// 配置路由守衛(wèi)router.beforeEach(async (to, from, next) => { ?if (!store.state.hasAuth) { ? ?await store.dispatch("setUserRouters"); ? ?// 獲取樹形權(quán)限路由 ? ?const newRoutes = generateRouter(store.state.TreeList); ? ?console.log(store.state.TreeList); ? ?newRoutes.forEach((route) => { ? ? ?router.addRoute(route); ? }); ? ?next({ to: to.path }); } else { ? ?next(); }});
首先通過調(diào)用actions中的方法,在actions中根據(jù)當(dāng)前用戶的id來異步請(qǐng)求數(shù)據(jù),然后在actions的方法中會(huì)調(diào)用mutations的方法將數(shù)據(jù)存儲(chǔ)到state中,然后再調(diào)用generateRouter方法獲取路由,在對(duì)獲取的路由數(shù)組通過遍歷調(diào)用addRoute來動(dòng)態(tài)的添加路由。
總結(jié)
通過這次對(duì)動(dòng)態(tài)路由的小案例的完成,使我對(duì)vue-router有了一個(gè)更深的認(rèn)知,以及在實(shí)際項(xiàng)目中對(duì)于動(dòng)態(tài)路由的實(shí)現(xiàn)都有了一個(gè)基本的思路,并且也學(xué)會(huì)了如何使用遞歸來將數(shù)據(jù)轉(zhuǎn)化為樹形結(jié)構(gòu)的數(shù)據(jù)。
到此這篇關(guān)于Vue中如何實(shí)現(xiàn)動(dòng)態(tài)路由的示例代碼的文章就介紹到這了,更多相關(guān)Vue 動(dòng)態(tài)路由內(nèi)容請(qǐng)搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!
相關(guān)文章:
