我刚开始使用 Vue 和 Pinia 我想显示登录用户的名字和姓氏,但是当我想在登录后访问用户ID时,它返回未定义 你能帮我解决这个问题吗 实际上我可以在登录页面上访问这些信息,但我想在登录后立即访问它们,当重定向到主页并转到其他页面时
这是我的 pinia 登录商店:
import { defineStore } from 'pinia'
import { axiosAPI } from '../axios'
export default defineStore('login', {
state: () => ({
user: [],
isLoading: false,
isuserLoggedIn: false,
token: '',
userInfo: [],
isRedirect: false,
userId: '',
}),
actions: {
async loginUser(values) {
this.isLoading = true
await axiosAPI
.post('user/login', values)
.then((response) => {
console.log(response)
this.isLoading = false
const data = response.data.data.payload
if (data) {
this.user = data
this.isuserLoggedIn = true
this.token = data.token
localStorage.setItem('token', this.token)
this.userId = this.user.id
this.isRedirect = true
setTimeout(() => {
window.location.href = '/home'
this.isRedirect = false
}, 20000)
}
})
.catch((error) => {
this.isLoading = false
})
this.getInfo(this.userId)
},
},
persist: true
})
这是我的个人资料组件:
<template>
<p
class="sm:text-neutral-950 sm:block hidden sm:text-sm sm:font-light pl-4"
:class="userProfile"
></p>
{{ userProfile }}
</template>
<script>
import useLoginStore from '../stores/login'
import { mapStores } from 'pinia'
export default {
name: 'Profile',
data() {
return {
usr: useLoginStore(),
}
},
computed: {
...mapStores(useLoginStore),
userProfile() {
return `${this.usr.userInfo.first_name} ${this.usr.userInfo.last_name}`
}
},
}
}
</script>
export default defineStore("login", {
state: () => ({
// ... (other state properties)
userId: localStorage.getItem("userId") || "", // Retrieve userId from localStorage
}),
actions: {
async loginUser(values) {
this.isLoading = true;
try {
// Make a POST request to the login endpoint
const response = await axiosAPI.post("user/login", values);
console.log(response);
// Update the loading state
this.isLoading = false;
// Extract user data from the response
const data = response.data.data.payload;
// Check if user data is available
if (data) {
// Update local state with user data
this.user = data;
this.isuserLoggedIn = true;
this.token = data.token;
// Store the token in localStorage for persistence
localStorage.setItem("token", this.token);
// Update the userId in local state
this.userId = this.user.id;
// Store the userId in localStorage for persistence
localStorage.setItem("userId", this.userId);
// Set a flag for redirection
this.isRedirect = true;
// Redirect to the home page after a delay
setTimeout(() => {
window.location.href = "/home";
this.isRedirect = false;
// No need to call getInfo here; it can be called in the created hook
// of the home page or another appropriate lifecycle hook
}, 20000);
}
} catch (error) {
// Handle errors and log them to the console
this.isLoading = false;
console.error(error);
}
},
},
});
为了防止页面刷新时userId丢失,将其持久保存在本地存储中至关重要。这确保了即使在页面重新加载后用户的身份也保持完整。在代码片段中,使用 localStorage.setItem('userId', this.userId) 存储 userId,确保其跨会话检索和保存。
然后使用 userId 进行 API 调用。