这是一个大bug,页面刷新持久化失效,只有一个store文件无法持久化,也就是说sessionStorage里存不进去。搞不懂真的搞不懂,
这是我在route.js文件里引用pinia的方式
import { userInfoStore } from '../stores/user';
const router = createRouter({
history: createWebHistory(),
routes: [
...
]
})
// 动态路由添加
export function initDyRoute() {
const user = userInfoStore()
let rightList = user.rightList;
...
}
router.beforeEach(async (to, from) => {
if (to.path === '/login') {
return true
} else {
// 动态添加路由,routes是拼装好的路由
initDyRoute()
if (!to.redirectedFrom) {
initDyRoute()
return { ...to, replace: true }
} else return true
}
})
export default router
页面一刷新,user.rightList里的数据就消失,持久化也没有用,别的store都可以持久化
最后的解决办法是手动添加sessionStorage
import { userInfoStore } from '../stores/user';
const router = createRouter({
history: createWebHistory(),
routes: [
...
]
})
// 动态路由添加
export function initDyRoute() {
const user = userInfoStore()
let rightList = user.rightList;
let r = sessionStorage.getItem('rightList')
if (r && rightList.length == 0) {
rightList = JSON.parse(r)
user.$patch((state: any) => {
state.rightList = rightList;
});
} else {
sessionStorage.setItem('rightList', JSON.stringify(rightList))
}
}
router.beforeEach(async (to, from) => {
if (to.path === '/login') {
return true
} else {
// 动态添加路由,routes是拼装好的路由
initDyRoute()
if (!to.redirectedFrom) {
initDyRoute()
return { ...to, replace: true }
} else return true
}
})
export default router
虽然解决了,但还是搞不懂为什么会这样,这是pinia天生的bug吗,希望有大佬解答