欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue中如何實現(xiàn)動態(tài)路由的示例代碼

 更新時間:2023年05月16日 09:09:32   作者:前端隨想  
本文主要介紹了Vue中如何實現(xiàn)動態(tài)路由的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

前言

我們在項目開發(fā)的過程中,難免會使用路由,那么我們在開發(fā)多角色的時,由于每個角色的權限不同,因此訪問到的頁面肯定也要有所限制,這個時候我們就需要使用動態(tài)路由

實現(xiàn)效果

使用的技術棧

  • 使用了koa2來作為后端
  • 使用vuex實現(xiàn)全局的數(shù)據(jù)共享
  • vue3的語法
  • 當然這里面還會使用一些算法(遞歸算法)

首先使用 vue create project-name 創(chuàng)建項目

后端使用koa2 項目名稱 從創(chuàng)建項目

實現(xiàn)思路

首先我們先來捋一下實現(xiàn)的思路:

  • 后端需要設計數(shù)據(jù),這個數(shù)據(jù)包含路由的路徑path,id ,pid(該路由的父級路由id),title 這里面是要顯示的內容
  • 同樣我們在前端可以模擬登錄,創(chuàng)建幾個用戶,然后我們給用戶設計的字段可以是這樣的 id(用戶id),name(用戶姓名)
  • auth(權限設置,是一個數(shù)組,表明可以訪問的路由的id)
  • 前端通過axios來訪問后端的數(shù)據(jù),然后獲取數(shù)據(jù)之后前端將其樹形化(使用遞歸算法),然后我們可以將其轉換為動態(tài)的路由結構(這部分可以封裝一個工具函數(shù)來實現(xiàn))
  • 我們可以借助vuex來實現(xiàn)axios的異步請求,通過mutations來將值賦值給state中定義的數(shù)據(jù)。這樣我們就可以實現(xiàn)全局的數(shù)據(jù)共享。

具體實現(xiàn)

首先我們來設計數(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: "學生管理",
  },
  {
 ?  id: 6,
 ?  pid: 5,
 ?  path: "operate",
 ?  name: "StudentOperate",
 ?  Link: "/student/operater",
 ?  title: "學生操作",
  },
  ...
];
?

當然這里面我只展示部分數(shù)據(jù),其實可以依次類推,我們不難發(fā)現(xiàn),pid是父級路由的id,這樣做就是為了后期將數(shù)據(jù)加工成樹形結構。

用戶的數(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],
  },
];
?

正如我們之前所說,這個用戶id包含這幾個字段,其中auth這個字段無疑是最重要的,他是一個數(shù)組,里面存的時路由的id,表明為用戶的訪問權限。

封裝一下axios函數(shù)

在這個小的項目里面,我們需要使用aixos函數(shù)來請求后端的數(shù)據(jù),那么我們和不妨封裝一個請求函數(shù),這樣更方便我們請求后端的數(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轉換為json字符串。這個封裝的函數(shù)最終會返回一個Promise.then()。

使用vuex實現(xiàn)全局數(shù)據(jù)共享

action部分

用來做異步請求,獲取后端的數(shù)據(jù),并且將其進行樹形化處理。

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中,便于進行全局訪問。

export default {
 ?// 更改權限
 ?setAuth(state, Auth) {
 ? ?state.hasAuth = Auth;
  },
 ?// 將數(shù)據(jù)存儲在state中
 ?setUserRouters(state, userRouters) {
 ? ?state.TreeList = userRouters;
  },
};
?

state部分

export default {
 ?uid: 1,
 ?hasAuth: false,
 ?TreeList: [],
};
?

將數(shù)據(jù)轉化為樹形化結構

function toTreeList(list, id = 0) {
 ?let res = [];
 ?list.forEach((item) => {
 ? ?if (item.pid === id) {
 ? ? ?item.children = toTreeList(list, item.id);
 ? ? ?// ? 這一步是為了是最里層的children會是空,應該刪除
 ? ? ?if (item.children.length == 0) delete item.children;
 ? ? ?res.push(item);
 ?  }
  });
 ?return res;
}

思路:

在這個封裝函數(shù)里面使用到了遞歸的思想,我們在設計數(shù)據(jù)的時候給每一個數(shù)據(jù)都設計了id和pid,那么最頂層元素的pid為0(沒有父級元素),其他子級都擁有pid,所以我們可以這樣操作,設計一個函數(shù),默認傳入從后端獲取到的數(shù)據(jù)list,和最頂層元素pid值(默認為0),然后我們對list進行遍歷,判斷l(xiāng)ist中的元素item的pid值與id是否相等,如果相等,那么item.children=toTreeList(list,item.id)來進行遞歸調用,這樣當pid和id值不相同時,就會執(zhí)行res.push(item)將元素push到res里面。

基礎路由模塊

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;

當輸入的路徑不存在時就會跳轉到NotFound這個組件顯示這個頁面

實現(xiàn)動態(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是經過樹形化處理的數(shù)據(jù),同樣這里面還是需要進行遞歸調用,這里對路由進行了配置,包括路由的路徑,名稱,都從后端獲取。然后判斷傳入的樹形結構數(shù)據(jù)是否含有子元素,如果有就遞歸調用給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");
 ? ?// 獲取樹形權限路由
 ? ?const newRoutes = generateRouter(store.state.TreeList);
 ? ?console.log(store.state.TreeList);
 ? ?newRoutes.forEach((route) => {
 ? ? ?router.addRoute(route);
 ?  });
 ? ?next({ to: to.path });
  } else {
 ? ?next();
  }
});

首先通過調用actions中的方法,在actions中根據(jù)當前用戶的id來異步請求數(shù)據(jù),然后在actions的方法中會調用mutations的方法將數(shù)據(jù)存儲到state中,然后再調用generateRouter方法獲取路由,在對獲取的路由數(shù)組通過遍歷調用addRoute來動態(tài)的添加路由。

總結 

通過這次對動態(tài)路由的小案例的完成,使我對vue-router有了一個更深的認知,以及在實際項目中對于動態(tài)路由的實現(xiàn)都有了一個基本的思路,并且也學會了如何使用遞歸來將數(shù)據(jù)轉化為樹形結構的數(shù)據(jù)。

到此這篇關于Vue中如何實現(xiàn)動態(tài)路由的示例代碼的文章就介紹到這了,更多相關Vue 動態(tài)路由內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論