常见的几个问题
- 刷新页面空白
- addRoute 没有加载完成就访问 -> next() 改成 next({…to, replace: true})
- 路由重名, 检查路由的name是否有重复
- 路由守卫死循环
- 添加一些条件, 比如: 判断是否已经获取到了路由数据
- 刷新页面会跳转到404页面
- 在动态路由添加完成后, 再添加404的路由
- Vite 的组件懒加载
const viteComponent = import.meta.glob("../views/**/*.vue")
component: viteComponent[`../views${item.path}.vue`]
贴一下路由守卫部分的代码
router.beforeEach((to, from, next) => {
clearPending()
if (to.path === "/login") {
next()
} else {
let token = getToken()
if (token && typeof token != "undefined") {
if (store.state.menus.length === 0) {
getRouters().then(() => {
next({
...to,
replace: true,
})
})
} else {
next()
}
} else {
next("/login")
}
}
})
const getRouters = () => {
return new Promise((resolve) => {
systemMenu.list().then((res) => {
store.dispatch("initMenu", res.data).then(() => {
let data = handlerRouterDate(res.data)
data.forEach((item: any) => {
router.addRoute("base", item)
})
router.addRoute("base", {
path: "/:w+",
name: "404Page",
component: () => import("@/views/404.vue"),
})
resolve(null)
})
})
})
}
const handlerRouterDate = (data: any) => {
let routerData = <any>[]
data.forEach((item: any) => {
if (item.children) {
let temp = handlerRouterDate(item.children)
temp.forEach((sub: any) => {
if (sub.router != "-") {
routerData.push(sub)
}
})
}
if (item.router != "-") {
routerData.push(handlerRouterItem(item))
}
})
return routerData
}
const handlerRouterItem = (item: any) => {
return {
path: item.router,
name: item.name,
component: viteComponent[`../views${item.path}.vue`],
}
}