【发布时间】:2021-08-04 15:20:40
【问题描述】:
我有这样一个问题:在pages/index.vue中加载nuxt布局之前需要获取localStorage数据
/pages/index.vue
<script>
export default {
layout (context) {
if (localStorage.getItem('AUTH_TOKEN')){
this.$store.dispatch('changeAuthStatus', {
authStatus: true,
accessToken: localStorage.getItem('AUTH_TOKEN'),
profileData: JSON.parse(localStorage.getItem('PROFILE_DATA'))
}).then(() => {
this.$store.dispatch('changeLoadedStatus', {
isLoaded: true
})
})
}
else {
this.$router.push('/auth')
}
}
</script>
页面加载时的错误:localStorage is not defined
也许我可以使用上下文获取 localStorage 数据?或者您可以向我推荐任何包,以便我可以在布局功能中使用它?
【问题讨论】:
-
顺便说一句,你在这里使用
layout? nuxtjs.org/docs/2.x/components-glossary/pages-layout你不是说middleware()吗? nuxtjs.org/docs/2.x/components-glossary/… -
是的,我使用
layout,我需要从localStorage中获取profileData来选择接下来要加载的布局 -
另外,更喜欢使用
async/await语法而不是.then。通常建议这样做。 -
我不知道它是否对你有帮助,但我主要使用通用存储来设置和检索令牌,使用 $storage.setUniversal() 和 $storage.getUniversal() 方法。 github.com/nuxt-community/universal-storage-module
-
@AmirhosseinShahbazi 感觉就像一个火箭筒,但很高兴看到这种解决方案确实存在。您可能应该将此作为答案发布,以便它可以被 OP 接受和投票!
标签: javascript vue.js nuxt.js vuex