引言
最近想嘗試 vue3 + elementplus + axios + pinia 封裝一個(gè)通用的后臺(tái)模板,寫到 vue-router 添加動(dòng)態(tài)路由時(shí),有一個(gè)不影響代碼運(yùn)行但是又有提示的報(bào)錯(cuò),因此進(jìn)行記錄,方便大家進(jìn)行解決
控制臺(tái)提示
圖片圈出的路由是動(dòng)態(tài)加載的路由
解決方案
404等報(bào)錯(cuò)頁面不再需要放在所有路由后面,可在一開始的時(shí)候就定義好報(bào)錯(cuò)跳轉(zhuǎn)的頁面路由。
頁面之所有一開始報(bào)錯(cuò)找不到路由,是因?yàn)閯?dòng)態(tài)加載的路由在 beforeEach 的時(shí)候 to.matched 為空數(shù)組,即此時(shí) next 跳轉(zhuǎn)則會(huì)出現(xiàn)空白頁面,之后使用 addRoute() 時(shí)動(dòng)態(tài)添加的路由已經(jīng)被加載上去,此時(shí) next({ …to, replace: true }) 就跳轉(zhuǎn)成功,所以需要在一開始先定義好 404 頁面,防止路由報(bào)上面圖片的錯(cuò)誤
export const Layout = () => import("@/layout/index.vue");
export const constantRoutes = [
{
path: "/",
redirect: "/dashboard",
hidden: true,
},
{
path: "/login",
name: "Login",
component: () => import("@/views/login/index.vue"),
hidden: true,
},
// 404頁面
{
path: "/:pathMatch(.*)*",
component: () => import("@/views/error/index.vue"),
hidden: true,
},
{
path: "/dashboard",
component: Layout,
redirect: "/dashboard/index",
hidden: true,
children: [
{
path: "index",
name: "Dashboard",
component: () => import("@/views/dashboard/index.vue"),
},
],
},
];
export default router;
import router, { resetRouter } from './router';
import { getToken } from '@/utils/sessionStorage';
import { usePermissionStore } from '@/store/permission';
// 判斷是否初次或者刷新頁面 0表示初次
let isRequest = 0;
router.beforeEach(async (to, _from, next) => {
async function init () {
// 調(diào)用方法獲取路由
const accessRoutes: any = await usePermissionStore().getGenerateRoutes();
accessRoutes.forEach((route: any) => {
router.addRoute(route);
});
isRequest = 1;
}
// 判斷條件根據(jù)項(xiàng)目更改
if (getToken()) {
if (to.path === '/login') {
next({ path: '/' });
}
if (isRequest) {
next();
} else {
await init();
next({ ...to, replace: true });
}
} else {
sessionStorage.clear();
isRequest = 0;
if (to.path === '/login') {
next();
} else {
resetRouter();
next({ path: '/login' });
}
}
});
注意
vue2 中 通常使用 path: " * " 捕獲所有路由,vue3 中不支持 vue2 的寫法,需要用正則來捕獲文章來源:http://www.zghlxwxcb.cn/news/detail-700261.html
1. /:pathMatch(.*)*
2. /:pathMatch(.*)
上面兩個(gè)的區(qū)別在于 如果省略最后一個(gè)'*'在解析或推送時(shí)將對(duì)params中的'/'字符進(jìn)行編碼
拓展
export const Layout = () => import("@/layout/index.vue");
// vue3 中,當(dāng)有使用到動(dòng)態(tài)加載路由的情況,使用這種方式引入會(huì)出現(xiàn)點(diǎn)擊每個(gè)大導(dǎo)航欄,Layout 重新加載的情況,因此需要改成上面的寫法
import Layout from "@/layout/index.vue";
點(diǎn)擊用戶管理中的任意路由之后,再點(diǎn)擊個(gè)人信息中的任意路由,如果使用上面第二種寫法,就會(huì)出現(xiàn) Layout 頁面組件重新加載!?。?/strong>文章來源地址http://www.zghlxwxcb.cn/news/detail-700261.html
到了這里,關(guān)于vue3 中動(dòng)態(tài)添加路由出現(xiàn)的問題 [Vue Router warn]: No match found for location with path “xxx“的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!