【发布时间】:2020-05-26 13:35:45
【问题描述】:
我使用 nuxt/auth 模块对我的 nuxt 网络应用程序进行了身份验证。我还使用模块化 vuex 商店来处理不同的状态。登录后,一切都很好,我可以正常浏览应用程序。但是当我尝试重新加载页面或直接通过 URL 访问它时,用户无法访问,因此整个网络应用程序变得无法使用。我尝试使用this.context.rootState.auth.user 访问用户对象,在页面重新加载或直接访问后为空。奇怪的是,这只发生在生产环境中。
我已经尝试添加一个 if-guard,但遗憾的是 getter 没有反应。可能是因为它是一个嵌套对象。这是我目前的吸气剂:
get someGetter() {
if (!this.context.rootState.auth.user) {
return []
}
const userId = this.context.rootState.auth.user.id as string
const arr = []
for (const item of this.items) {
// Using userId to add something to arr
}
return arr
}
有没有办法强制 nuxt 在初始化 vuex 模块之前完成身份验证,或者让这个 getter 反应,所以当用户对象可访问时它会再次触发?
这是我的 auth-config 在 nuxt.config.ts 中的样子:
auth: {
strategies: {
local: {
_scheme: '@/auth/local-scheme',
endpoints: {
login: {
url: '/api/authenticate',
method: 'post',
propertyName: false
},
logout: { url: '/api/logout', method: 'post' },
user: { url: '/api/users/profile', propertyName: false }
}
},
// This dummy setting is required so we can extend the default local scheme
dummy: {
_scheme: 'local'
}
},
redirect: {
logout: '/login'
}
}
编辑
我通过关注Raihan Kabir´s answer 解决了这个问题。在身份验证插件中使用vuex-persistedstate,每次服务器呈现页面时都会触发该插件。该插件将 userId 保存在 cookie 中,因此如果 auth-module 未准备好,商店可以将其用作后备。
【问题讨论】:
-
同样的问题。