Vue3實現(xiàn)動態(tài)路由與手動導航
在后臺管理系統(tǒng)中,前端的路由往往需要根據(jù)用戶的權限動態(tài)生成。這篇文章將重點介紹如何在 Vue 3 中實現(xiàn)動態(tài)路由注冊和手動導航,確保用戶訪問的頁面與權限對應。
1. 動態(tài)路由的需求與原理
為什么需要動態(tài)路由?
- 權限控制:不同用戶角色需要看到不同的菜單和頁面。
- 后端驅動:后端返回菜單數(shù)據(jù),前端動態(tài)渲染菜單和注冊路由。
- 避免硬編碼:路由不再寫死在前端代碼里,保證靈活性。
動態(tài)路由的原理
- 靜態(tài)路由:定義公共頁面,如登錄頁和404頁面。
- 動態(tài)路由:存儲需要通過后端數(shù)據(jù)動態(tài)添加的頁面。
- 動態(tài)注冊路由:根據(jù)后端返回的數(shù)據(jù),通過
router.addRoute
動態(tài)添加到路由系統(tǒng)。 - 手動導航:添加新路由后,需要手動觸發(fā)導航以保證路由生效。
2. 靜態(tài)路由與動態(tài)路由配置
靜態(tài)路由
靜態(tài)路由是所有用戶共享的基本路由,如登錄頁、404頁等。
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'; import Layout from '@/layout/admin.vue'; const routes: Array<RouteRecordRaw> = [ { path: '/', component: Layout, name: 'admin', }, { path: '/login', name: 'login', component: () => import('@/pages/login/index.vue'), meta: { title: '登錄頁' }, }, { path: '/:pathMatch(.*)*', name: 'NotFound', component: () => import('@/pages/404/index.vue'), meta: { title: '404' }, }, ];
動態(tài)路由
動態(tài)路由需要根據(jù)后端返回的數(shù)據(jù)進行注冊:
const asyncRoutes: Array<RouteRecordRaw> = [ { path: '/', name: '/', component: () => import('@/pages/index/index.vue'), meta: { title: '首頁' }, }, { path: '/goods/list', name: '/goods/list', component: () => import('@/pages/goods/list.vue'), meta: { title: '商品列表' }, }, { path: '/category/list', name: '/category/list', component: () => import('@/pages/category/list.vue'), meta: { title: '分類列表' }, }, ];
3. addRoutes 實現(xiàn)動態(tài)路由注冊
addRoutes 方法
該方法接收后端返回的菜單數(shù)組,并將匹配的動態(tài)路由添加到主路由 admin
下。
import { router } from '@/router/index'; export const addRoutes = (routesArray: Array<MenusArray>) => { let hasNewRoutes = false; const addRoutesFromMenus = (menus: Array<MenusArray>) => { menus.forEach((menu) => { // 查找匹配的動態(tài)路由 const route = asyncRoutes.find((r) => r.path === menu.frontpath); // 添加到router中 if (route && !router.hasRoute(route.path)) { router.addRoute('admin', route); hasNewRoutes = true; } // 遞歸處理子菜單 if (menu.child && menu.child.length > 0) { addRoutesFromMenus(menu.child); } }); }; addRoutesFromMenus(routesArray); return hasNewRoutes; };
解釋
router.addRoute
:Vue Router 提供的 API,可以動態(tài)添加路由。- 避免重復添加:
router.hasRoute
檢查路由是否已存在,防止重復注冊。 - 遞歸處理:支持多級菜單,遞歸遍歷
child
子菜單。
4. 路由守衛(wèi)中調(diào)用 addRoutes
在 router.beforeEach
路由守衛(wèi)中,調(diào)用 addRoutes
注冊動態(tài)路由,并實現(xiàn)手動導航。
import { getToken } from '@/utils/auth'; import store from '@/store'; import { addRoutes } from '@/router/index'; router.beforeEach(async (to, from, next) => { const token = getToken(); let hasNewRoutes = false; // 顯示全局加載狀態(tài) showFullLoading(); // 未登錄跳轉到登錄頁 if (!token && to.name !== 'login' && to.name !== 'NotFound') { return next('/login'); } // 已登錄訪問登錄頁,重定向到主頁 if (token && to.name === 'login') { return next('/'); } // 已登錄狀態(tài)下,動態(tài)添加路由 if (token) { await store.dispatch('user/getUserInfo'); // 拉取用戶信息 hasNewRoutes = addRoutes(store.getters['menu/getMenus']); // 添加動態(tài)路由 } // 設置頁面標題 if (to.meta.title) { document.title = `${to.meta.title}-測試后臺管理`; } else { document.title = '測試后臺管理'; } // 手動導航:如果添加了新路由,重新跳轉當前頁面 hasNewRoutes ? next(to.fullPath) : next(); });
手動導航的必要性
router.addRoute
是動態(tài)操作,添加新路由后需要重新跳轉一次,確保用戶能正常訪問新注冊的頁面。next(to.fullPath)
:手動跳轉到當前頁面。
5. 完整流程
- 用戶登錄:獲取用戶
token
,拉取用戶信息。 - 獲取菜單數(shù)據(jù):后端返回用戶權限對應的菜單數(shù)據(jù)。
- 動態(tài)注冊路由:調(diào)用
addRoutes
將菜單數(shù)據(jù)匹配的路由添加到admin
下。 - 手動導航:動態(tài)路由添加完成后,使用
next(to.fullPath)
手動觸發(fā)頁面跳轉。 - 權限生效:用戶只能訪問與自己權限匹配的頁面。
6. 總結
- 靜態(tài)路由:用于公共頁面。
- 動態(tài)路由:后端驅動,通過
addRoutes
動態(tài)注冊。 - 手動導航:解決動態(tài)添加路由后無法直接訪問的問題。
- 靈活性:動態(tài)路由使前端代碼更靈活,后端控制權限更方便。
以上就是Vue3實現(xiàn)動態(tài)路由與手動導航的詳細內(nèi)容,更多關于Vue3動態(tài)路由與手動導航的資料請關注腳本之家其它相關文章!
相關文章
詳解vue中使用axios對同一個接口連續(xù)請求導致返回數(shù)據(jù)混亂的問題
這篇文章主要介紹了詳解vue中使用axios對同一個接口連續(xù)請求導致返回數(shù)據(jù)混亂的問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11解決vue項目運行出現(xiàn)warnings?potentially?fixable?with?the?`--fix
這篇文章主要介紹了解決vue項目運行出現(xiàn)warnings?potentially?fixable?with?the?`--fix`?option的報錯問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2021-11-11詳解vue 中使用 AJAX獲取數(shù)據(jù)的方法
本篇文章主要介紹了詳解vue 中使用 AJAX獲取數(shù)據(jù)的方法,在VUE開發(fā)時,數(shù)據(jù)可以使用jquery和vue-resource來獲取數(shù)據(jù),有興趣的可以了解一下。2017-01-01