1、刷新保持state
在 app.vue中的created函数中写如下代码:localstorage和sessionStorage都可以
//在页面加载时读取sessionStorage里的状态信息
if (sessionStorage.getItem("store") ) {
this.$store.replaceState(Object.assign({},this.$store.state,JSON.parse(sessionStorage.getItem("store"))))
}
//在页面刷新时将vuex里的信息保存到sessionStorage里
window.addEventListener("beforeunload",()=>{
sessionStorage.setItem("store",JSON.stringify(this.$store.state))
})
2、路由拦截
在 main.js 中判断是否需要登录
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
//这里判断用户是否登录,验证本地存储是否有token
if (!localStorage.token) { // 判断当前的token是否存在
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next() // 确保一定要调用 next()
}
})
在路由配置文件中 (router.js) 给需要登录的路由加一个meta
{
path: '/mint',
component: Mint,
meta: { requiresAuth: true } // 添加表示需要验证
}
本文介绍如何在Vue应用中实现Vuex状态的持久化存储及页面刷新后的状态恢复,并通过路由守卫来控制未登录用户的访问权限。
3756

被折叠的 条评论
为什么被折叠?



