使用 nuxt-auth 成功验证后如何获取用户信息

How to get user info after a successful authentication with nuxt-auth

我正在使用 nuxt.js,在我向后端发送一个带有电子邮件和密码的登录请求后,我收到一个包含消息、令牌和用户信息的响应,我如何在响应并在成功登录后将其保存在 store.js 中的某个状态? 我想在 store/index.js 中使用可能在成功登录后调度的操作 saveUserAction 将用户对象保存在用户状态下,我不知道那是不是对与不对,任何建议都会很有帮助

回应

{
  "message":"success",
  "token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiNzFkYjA1MWM2MTYxMmE4YzAyNWI2YjU3N2xMzJiNzJjMjI0MzRlY2IzNzYwNTg2N2NjOWQ5ZWEwY2MiMJM3uYEiZ8GSlPlQhIctVErO2KzwXOBxifWWoM7et_qT-mgvfsk3ljwiQF9iPQw-WeekBx8J8lcmxDLESa3tfE1Re1Xk2flkcBLmiI4JN2YHh08U1U",
  "user":{
    "id":1,
    "role_id":4587,
    "firstname":"Hans",
    "lastname":"newman",
    "email":"newman@gmail.com",
    "email_verified_at":null,
    "phone":"89498",
    "skype":"gdgdfg",
    "birthdate":"2021-05-02",
    "address":"asdfaf",
    "postalcode":14984,
    "city":"jisf",
    "country":"isfisf",
    "status":"mfof",
    "created_at":"2021-06-16T09:33:08.000000Z",
    "updated_at":"2021-06-16T09:39:41.000000Z",
    "image":"1623835988-carlsen.png",
    "description":"sfdgg",
    "geo_lat":5.5,
    "geo_lng":8.1
  }
}

login.vue

<script>
import { mapActions } from 'vuex'

export default {
  data() {
    return {
      auth: false,
      email: '',
      password: '',
    }
  },

  methods: {
    async login() {
      const succesfulLogin = await this.$auth.loginWith('local', {
        data: {
          email: this.email,
          password: this.password,
        },
      })

      if (succesfulLogin) {
        await this.$auth.setUser({
          email: this.email,
          password: this.password,
        })
        this.$router.push('/profile')
      }
    },
  },
}
</script>

store/index.js

export const state = () => ({
  user:{}
})
  
export const mutations = {
  saveUser(state, payload) {
    state.user=payload;
  }
}

export const actions = {
   saveUserAction({commit}, UserObject){
      commit('saveUser');
   }
}

转到您的 vue devtools、vuex 选项卡并查找 auth,它应该已经可用。这个答案可能会在您调试期间对您有所帮助:

由于您在响应中确实有 user 对象,因此这种配置应该可以做到,如 documentation 所示。不需要做一些其他的 vuex 动作。

auth: {
  strategies: {
    local: {
      token: {
        property: 'token',
        global: true,
      },
      user: {
        property: 'user', // the name of your object in your backend response payload
      },
      endpoints: {
        [...]
      }
    }
  }
}