首页 > 解决方案 > this.$auth.loggedIn 返回 false

问题描述

当我从 nuxtjs 发送登录请求时,我在后端使用 laravel/passport 进行身份验证,并使用 nuxtjs 作为前端,如果登录成功,我会作为响应返回令牌和用户信息,然后用户将被重定向到/profile页面,但是/profile当我返回页面时,我 this.$auth.loggedIn得到了false

登录.vue

<script>
export default {
  data() {
    return {
      auth: false,
      email: "",
      password:""
    }
  },
  methods: {
    async login() {
      try {
        const data = { email: this.email, password: this.password }
        await this.$auth.loginWith('local', { data:data})
        .then(() => this.$router.push('/profile'))
      } catch (e) {
      }
    }
  }
}
</script>

个人资料.vue

<template>
  <div class="mt-6">loggedInUser: {{ loggedInUser }}</div>
</template>

<script>
export default{
  data() {
    return {
      loggedInUser:this.$auth.loggedIn
    }
  }
}

nuxt.config.js

auth: {
  strategies: {
    provider: 'laravel/passport',
    local: {
      user: {
        property: false,
        autoFetch: true
      },
      endpoints: {
        login: { url: '/login', method: 'post', propertyName: 'token' }, 
        user: { url: '/user', method: 'get' }
      },
      clientId: 'cleint_id',
      clientSecret: 'client_secret'
    }
  }
},

modules: [
  '@nuxtjs/axios',
  // https://go.nuxtjs.dev/bootstrap
  'bootstrap-vue/nuxt',
  '@nuxtjs/auth',
],

axios: {
  baseURL: "http://prostudent.test/api"
},

以及由于登录发生在后端,nuxt 如何知道用户已登录?

这是直接在我点击登录后,我被重定向到个人资料,登录的响应如预期的那样,消息,令牌和信息,但在/profile页面中似乎我没有登录!

这直接在我点击登录后

标签: vue.jsnuxt.js

解决方案


即使您没有在自己的模块中使用 Vuex,也会为您nuxt/auth创建一些状态。因此存在this.$store.state.auth.loggedIn. 顺便说一句,您是否尝试$storeprofile.vue文件上附加?如文档所示。

像这样

<template>
  <div class="mt-6">
    loggedInUser: {{ $store.state.auth.loggedIn }}
  </div>
</template>

另外,打开您的 vue devtools 并检查 vuex 选项卡,您会在那里找到一些不错的状态。

在此处输入图像描述

这也回答了你的另一个问题

以及由于登录发生在后端,nuxt 如何知道用户已登录?

Nuxt 检查来自服务器的响应,并根据它,将状态设置auth.loggedIntrueor 或false


这些是实现成功登录所需的 2 个步骤。

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,
  })
}

之后,loggedIn可以传给true

当然,user信息也可以从后端获取。取决于您的用例。


推荐阅读