vue.js - 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
页面中似乎我没有登录!
解决方案
即使您没有在自己的模块中使用 Vuex,也会为您nuxt/auth
创建一些状态。因此存在this.$store.state.auth.loggedIn
. 顺便说一句,您是否尝试$store
在profile.vue
文件上附加?如文档所示。
像这样
<template>
<div class="mt-6">
loggedInUser: {{ $store.state.auth.loggedIn }}
</div>
</template>
另外,打开您的 vue devtools 并检查 vuex 选项卡,您会在那里找到一些不错的状态。
这也回答了你的另一个问题
以及由于登录发生在后端,nuxt 如何知道用户已登录?
Nuxt 检查来自服务器的响应,并根据它,将状态设置auth.loggedIn
为true
or 或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
信息也可以从后端获取。取决于您的用例。
推荐阅读
- reactjs - 当我设置相同的状态值时,如何避免触发 useEffect?
- sql - MariaDB 如何处理已经系统版本化的表
- python - 能不能用pandas过滤亿万行数据
- javascript - 如何根据订单号通过文本删除特定的 Li 标签?
- html - 为什么这些框不能垂直对齐?
- javascript - for ... 在 if 语句之后的语句中
- swift - 关于 swift5 和 alamofire5,如何使用 AF.request 检查登录是否成功?
- java - Spring Batch 中 SimpleJobBuilder 和 FlowJobBuilder 的区别?
- c++ - 有没有办法让 CGAL 的折线简化适用于内部/共享边界?
- javascript - 如何在 sass 中访问环境变量?