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

vue.js Vue.js

十三西门

2020-03-23

我使用nuxt / auth模块在nuxt Web应用程序上进行了身份验证。我还使用模块化Vuex存储来处理不同的状态。登录后,一切都很好,我可以正常浏览该应用程序。但是,当我尝试重新加载页面或直接通过URL访问页面时,无法访问用户,因此,整个Web应用程序将变得无法使用。我尝试使用来访问用户对象this.context.rootState.auth.user,页面重新加载或直接访问后,该对象为null。奇怪的是,这仅在生产中发生。

我已经尝试添加一个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的回答解决了这个问题在auth插件中使用vuex-persistedstate,每次服务器呈现页面时都会触发该插件。该插件将userId保存在cookie中,因此如果auth模块尚未准备好,则商店可以将其用作备用。

第3048篇《重新加载页面或直接访问后,无法在vuex模块中访问身份验证》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android