Vue3實(shí)現(xiàn)動(dòng)態(tài)路由與手動(dòng)導(dǎo)航
在后臺管理系統(tǒng)中,前端的路由往往需要根據(jù)用戶的權(quán)限動(dòng)態(tài)生成。這篇文章將重點(diǎn)介紹如何在 Vue 3 中實(shí)現(xiàn)動(dòng)態(tài)路由注冊和手動(dòng)導(dǎo)航,確保用戶訪問的頁面與權(quán)限對應(yīng)。
1. 動(dòng)態(tài)路由的需求與原理
為什么需要?jiǎng)討B(tài)路由?
- 權(quán)限控制:不同用戶角色需要看到不同的菜單和頁面。
- 后端驅(qū)動(dòng):后端返回菜單數(shù)據(jù),前端動(dòng)態(tài)渲染菜單和注冊路由。
- 避免硬編碼:路由不再寫死在前端代碼里,保證靈活性。
動(dòng)態(tài)路由的原理
- 靜態(tài)路由:定義公共頁面,如登錄頁和404頁面。
- 動(dòng)態(tài)路由:存儲需要通過后端數(shù)據(jù)動(dòng)態(tài)添加的頁面。
- 動(dòng)態(tài)注冊路由:根據(jù)后端返回的數(shù)據(jù),通過
router.addRoute動(dòng)態(tài)添加到路由系統(tǒng)。 - 手動(dòng)導(dǎo)航:添加新路由后,需要手動(dòng)觸發(fā)導(dǎo)航以保證路由生效。
2. 靜態(tài)路由與動(dòng)態(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' },
},
];
動(dòng)態(tài)路由
動(dòng)態(tài)路由需要根據(jù)后端返回的數(shù)據(jù)進(jìn)行注冊:
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 實(shí)現(xiàn)動(dòng)態(tài)路由注冊
addRoutes 方法
該方法接收后端返回的菜單數(shù)組,并將匹配的動(dòng)態(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) => {
// 查找匹配的動(dòng)態(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,可以動(dòng)態(tài)添加路由。- 避免重復(fù)添加:
router.hasRoute檢查路由是否已存在,防止重復(fù)注冊。 - 遞歸處理:支持多級菜單,遞歸遍歷
child子菜單。
4. 路由守衛(wèi)中調(diào)用 addRoutes
在 router.beforeEach 路由守衛(wèi)中,調(diào)用 addRoutes 注冊動(dòng)態(tài)路由,并實(shí)現(xiàn)手動(dòng)導(dǎo)航。
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();
// 未登錄跳轉(zhuǎn)到登錄頁
if (!token && to.name !== 'login' && to.name !== 'NotFound') {
return next('/login');
}
// 已登錄訪問登錄頁,重定向到主頁
if (token && to.name === 'login') {
return next('/');
}
// 已登錄狀態(tài)下,動(dòng)態(tài)添加路由
if (token) {
await store.dispatch('user/getUserInfo'); // 拉取用戶信息
hasNewRoutes = addRoutes(store.getters['menu/getMenus']); // 添加動(dòng)態(tài)路由
}
// 設(shè)置頁面標(biāo)題
if (to.meta.title) {
document.title = `${to.meta.title}-測試后臺管理`;
} else {
document.title = '測試后臺管理';
}
// 手動(dòng)導(dǎo)航:如果添加了新路由,重新跳轉(zhuǎn)當(dāng)前頁面
hasNewRoutes ? next(to.fullPath) : next();
});手動(dòng)導(dǎo)航的必要性
router.addRoute是動(dòng)態(tài)操作,添加新路由后需要重新跳轉(zhuǎn)一次,確保用戶能正常訪問新注冊的頁面。next(to.fullPath):手動(dòng)跳轉(zhuǎn)到當(dāng)前頁面。
5. 完整流程
- 用戶登錄:獲取用戶
token,拉取用戶信息。 - 獲取菜單數(shù)據(jù):后端返回用戶權(quán)限對應(yīng)的菜單數(shù)據(jù)。
- 動(dòng)態(tài)注冊路由:調(diào)用
addRoutes將菜單數(shù)據(jù)匹配的路由添加到admin下。 - 手動(dòng)導(dǎo)航:動(dòng)態(tài)路由添加完成后,使用
next(to.fullPath)手動(dòng)觸發(fā)頁面跳轉(zhuǎn)。 - 權(quán)限生效:用戶只能訪問與自己權(quán)限匹配的頁面。
6. 總結(jié)
- 靜態(tài)路由:用于公共頁面。
- 動(dòng)態(tài)路由:后端驅(qū)動(dòng),通過
addRoutes動(dòng)態(tài)注冊。 - 手動(dòng)導(dǎo)航:解決動(dòng)態(tài)添加路由后無法直接訪問的問題。
- 靈活性:動(dòng)態(tài)路由使前端代碼更靈活,后端控制權(quán)限更方便。
以上就是Vue3實(shí)現(xiàn)動(dòng)態(tài)路由與手動(dòng)導(dǎo)航的詳細(xì)內(nèi)容,更多關(guān)于Vue3動(dòng)態(tài)路由與手動(dòng)導(dǎo)航的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
詳解vue中使用axios對同一個(gè)接口連續(xù)請求導(dǎo)致返回?cái)?shù)據(jù)混亂的問題
這篇文章主要介紹了詳解vue中使用axios對同一個(gè)接口連續(xù)請求導(dǎo)致返回?cái)?shù)據(jù)混亂的問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
解決vue項(xiàng)目運(yùn)行出現(xiàn)warnings?potentially?fixable?with?the?`--fix
這篇文章主要介紹了解決vue項(xiàng)目運(yùn)行出現(xiàn)warnings?potentially?fixable?with?the?`--fix`?option的報(bào)錯(cuò)問題,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2021-11-11
vue計(jì)算屬性+vue中class與style綁定(推薦)
這篇文章主要介紹了vue計(jì)算屬性+vue中class與style綁定,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-03-03
HTML頁面中使用Vue示例進(jìn)階(快速學(xué)會(huì)上手Vue)
Vue是用于構(gòu)建用戶界面的漸進(jìn)式JavaScript框架。特色:構(gòu)建用戶界面—數(shù)據(jù)變成界面;漸進(jìn)式—Vue可以自底向上逐層的應(yīng)用。VUE有兩種使用方式,一種實(shí)在html中直接使用vue做開發(fā),一種是企業(yè)級的單頁面應(yīng)用。2023-02-02
詳解vue 中使用 AJAX獲取數(shù)據(jù)的方法
本篇文章主要介紹了詳解vue 中使用 AJAX獲取數(shù)據(jù)的方法,在VUE開發(fā)時(shí),數(shù)據(jù)可以使用jquery和vue-resource來獲取數(shù)據(jù),有興趣的可以了解一下。2017-01-01

