首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在使用nuxt-auth成功身份验证后获取用户信息

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

Stack Overflow用户
提问于 2021-06-25 10:39:44
回答 1查看 2.9K关注 0票数 1

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

响应

代码语言:javascript
复制
{
  "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

代码语言:javascript
复制
<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

代码语言:javascript
复制
export const state = () => ({
  user:{}
})
  
export const mutations = {
  saveUser(state, payload) {
    state.user=payload;
  }
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-25 10:53:23

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

由于您的user对象在响应中,这种配置应该这样做,如文档所示。不需要做其他的性行为。

代码语言:javascript
复制
auth: {
  strategies: {
    local: {
      token: {
        property: 'token',
        global: true,
      },
      user: {
        property: 'user', // the name of your object in your backend response payload
      },
      endpoints: {
        [...]
      }
    }
  }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68129637

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档