问题描述:
作者发现使用Ant Design Pro中存在一个问题,页面刷新后vuex数据丢失,导致UserInfo找不到影响页面的问题,故而写此文,望能助有需之人。
原因分析:
提示:Vuex的机制问题
vuex是存在浏览器页面内存的数据,所以刷新后就没有了,虽然很多人认为存在localstorage或者sessionstorage内不安全,但作者还是习惯存在浏览器内存。
解决方案:
1.src/store/modules/user.js Login方法内存在LocalStorage中
2.src/permission.js 对应调整
作者的做法是让每一次原项目中的获取getInfo接口至vuex的机制,改为从localstorage中获取,是不是非常的机灵鬼呢 *~*
user.js
// 登录
Login ({ commit }, userInfo) {
return new Promise((resolve, reject) => {
login(userInfo).then(response => {
const result = response.data
storage.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
storage.set(REFRESH_TOKEN, result.refresh, 7 * 24 * 60 * 60 * 1000)
storage.set(USER_INFO,result.userInfo,7 * 24 * 60 * 60 * 1000)
commit('SET_INFO', result.userInfo)
commit('SET_TOKEN', result.token)
commit('SET_NAME', { name: result.userInfo.name, welcome: welcome() })
resolve(response)
}).catch(error => {
reject(error)
})
})
},
permission.js
router.beforeEach((to, from, next) => {
NProgress.start() // start progress bar
to.meta && typeof to.meta.title !== 'undefined' && setDocumentTitle(`${i18nRender(to.meta.title)} - ${domTitle}`)
/* has token */
console.log(store);
if (storage.get(ACCESS_TOKEN) && storage.get(USER_INFO)) { //是否存在token和UserInfo
// 每次变动都存储到vuex中
store.commit('SET_INFO', storage.get(USER_INFO))
store.commit('SET_TOKEN', storage.get(ACCESS_TOKEN))
store.commit('SET_NAME', { name: storage.get(USER_INFO).name, welcome: welcome() })
next()
} else {
if (allowList.includes(to.name)) {
// 在免登录名单,直接进入
next()
} else {
next({ path: loginRoutePath, query: { redirect: to.fullPath } })
NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
}
}
})
去尝试吧。