vue3项目动态路由的相关配置踩坑记录
1.路由文件中引入store的报错解决
import { useUserStore } from '@/stores/user' // 错误:此时 Pinia 未初始化const store = useUserStore() // 报错
解决方案:
import pinia,{ useUserStore } from '@/stores/user' 或者在路由前置守卫中调用useUserStore()
2..路由懒加载import中动态绑定变量问题,会报failed to resolve specificer 'xx.vue' 这个错误
component: () => import(route.component) //这种写法会报错
解决方案:
使用 import.meta.glob
预先声明所有可能路径
const modules=import.meta.glob('@/views/**/*.vue')
component: modules[`/src/views/${route.component}.vue`] // 匹配映射
3.本地存储路由对象时component存储为空问题
原因:函数不可序列化
component: () => import('...')
是一个函数,而 localStorage
只能存储字符串(通过 JSON.stringify()
转换时会丢失函数)
解决方案:componet:存普通的字符串,最后在使用时再转换为路由懒加载的写法()=>import('...')
4.动态路由添加完毕之后页面跳转空白问题
原因:使用 router.addRoute()
动态添加路由后立即跳转时,可能会遇到路由未完全加载导致跳转失败的问题
解决方案举例: next({ ...to, replace: true }) // 重试当前导航
router.beforeEach((to, from, next) => {if (需要动态路由且尚未加载) {loadDynamicRoutes().then(() => {next({ ...to, replace: true }) // 重试当前导航})} else {next()}
})