使用的vite+vue3+pinia来实现动态路由
pinia已经做了持久化
问题:
从登录进入页面一切正常,所有动态路由能够添加到router,控制台打印也是正常;按f5刷新后,在登录逻辑里动态添加的路由都消失了。打印存在pinia中的用户路由发现其他属性都有,但是component属性直接不见了。求解惑
添加动态路由代码:
router.beforeEach((to, from, next) => {
const user = userStore()
const { token, roles, routes } = storeToRefs(user)
if (token.value) {
if (to.path === routePaths.login) {
next({ path: routePaths.default })
} else {
if (roles.value.length === 0) {
user.getRoles().then(() => {
user.initRoutes().then(() => {
resetRouter()
routes.value.forEach(route => {
let index = constantRoutes.findIndex(r => r.name === route.name)
if (index != -1) {
constantRoutes[index].children = route.children
}
});
constantRoutes.forEach(route => {
router.addRoute(route)
})
console.log(routes.value)
const redirect = decodeURIComponent(from.query.redirect as string || to.path)
if (to.path === redirect) {
next({ ...to, replace: true })
} else {
next({ path: redirect })
}
})
})
} else {
console.log(routes.value)
console.log(router.getRoutes())
next()
}
}
} else {
if (whiteList.includes(to.name as string) || whiteList.includes(to.path)) {
next()
} else {
next({ path: routePaths.login, query: { redirect: to.fullPath } })
}
}
})
initRoutes(): Promise<void> {
return new Promise((resolve, reject) => {
generatorDynamicRouter().then(res => {
this.routes = res
console.log(this.routes)
resolve()
}).catch(err => {
reject(err)
})
})
generatorDynamicRouter就是请求list数据,然后将list转换成tree返回一个树状结构的路由数组,输出的数据样子
vite的组件动态引入:
const modules = import.meta.glob(['../views/**/*.vue', '../components/**/*.vue'])
export const generatorDynamicRouter = (): Promise<Array<RouteRecordRaw>> => {
return new Promise((resolve, reject) => {
getMenus()
.then(res => {
const { data } = res
const menuNav = []
const childrenNav = []
listToTree(data, childrenNav, '')
rootRouter.children = childrenNav
menuNav.push(rootRouter)
const asyncRoutes = generator(menuNav)
// routers.push(notFoundRouter)
resolve(asyncRoutes)
})
.catch(err => {
reject(err)
})
})
}
export const generator = (routerMap, parent?) => {
return routerMap.map(item => {
const { title, show, hideChildren, hiddenHeaderContent, target, icon } = item.meta || {}
const currentRouter = {
path: item.path || `${(parent && parent.path) || ''}/${item.name}`,
name: item.name || '',
label: item.label || '',
component: modules[`../views/${item.component}.vue`],
children: []
}
if (item.children && item.children.length > 0) {
currentRouter.children = generator(item.children, currentRouter)
}
return currentRouter
})
}
这是正常登陆后
打印存储的用户路由(44行打印),和router.getRoutes()方法获取到的路由
刷新页面后变成这样了