页面重新加载或直接访问后无法在 vuex-module 中访问身份验证

Udo*_*ada 6 vue.js vuex nuxt.js

我使用 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
  }
Run Code Online (Sandbox Code Playgroud)

有没有办法在初始化 vuex 模块之前强制 nuxt 完成身份验证,或者使这个 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'
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑

我按照Raihan Kabir 的回答解决了这个问题。在 auth-plugin 中使用vuex-persistedstate,每次服务器渲染页面时都会触发。该插件将 userId 保存在 cookie 中,因此如果 auth-module 未准备好,商店可以将其用作后备。

Rai*_*bir 6

问题是,vuex在重新加载/刷新时清除数据以确保凭据安全。就是这样vuex。如果您想在重新加载后长时间存储数据而不中断,您应该使用localstorage。但是不建议使用localstorage来存储凭据。

如果您只user_id需要保留在 中vuex,请改用Cookie。并在您商店的index.js文件中尝试这样的操作 -

export const actions = {
    // This one runs on the beginning of reload/refresh
    nuxtServerInit ({ commit }, { req }) {
        if (req.headers.cookie) {
              const parsed = cookieparser.parse(req.headers.cookie)
              try {
                  // get user id that you would set on auth as Cookie
                  user_id = parsed.uid
              } catch (err) {
                  // error here...
              }
        }

        // perform login and store info on vuex store
        commit('authUserOnReload', user_id)
    },
}

// Define Mutations
export const mutations = {
    authUserOnReload (state, user_id) {
        // perform login here and store user
    }
}
Run Code Online (Sandbox Code Playgroud)