1

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

回复

{
  "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
  }
}

登录.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>

存储/index.js

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

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

在此处输入图像描述

4

1 回答 1

1

转到您的 vue devtools,vuex 选项卡并查找auth,它应该已经可用。此答案可能会在您的调试过程中对您有所帮助:https ://stackoverflow.com/a/68081536/8816585

由于您user在响应中确实有您的对象,因此这种配置应该做到这一点,如文档中所示。无需进行其他一些 vuex 操作。

auth: {
  strategies: {
    local: {
      token: {
        property: 'token',
        global: true,
      },
      user: {
        property: 'user', // the name of your object in your backend response payload
      },
      endpoints: {
        [...]
      }
    }
  }
}
于 2021-06-25T10:53:23.493 回答