You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
bloggingplatform/src/stores/user.ts

104 lines
2.9 KiB

// src/stores/user.ts
import type { IUserInfo } from '@/model/model';
import { defineStore } from 'pinia';
export const useUserStore = defineStore('users', {
state: () => ({
users: JSON.parse(localStorage.getItem('users') || '[]') as IUserInfo[], // 从localStorage加载已注册用户
currentUser: null as IUserInfo | null, // 当前登录的用户
}),
actions: {
// 注册用户
registerUser(user :IUserInfo) {
// 检查用户名是否已存在
const userExists = this.users.some((u: IUserInfo) => u.username === user.username);
if (userExists) {
return "用户已存在"
}
// 检查是不是管理员
if (user.username === "admin") {
return "管理员账号,不可使用"
}
// 如果用户名不存在,将新用户保存到数组中
this.users.push(user);
// 更新到 localStorage
localStorage.setItem('users', JSON.stringify(this.users));
return "成功"
},
// 登录用户
loginUser(username: string, password: string) {
if (username === 'admin' && password === '123456') {
// 模拟管理员登录
this.currentUser = {
username: 'admin',
nickname: '管理员',
signature: '我是系统管理员',
phone: '',
birthday: '1999-01-01',
isAdmin: true, // 设置管理员标识
password: '123456',
};
return this.currentUser
}
// 查找匹配的用户
const user = this.users.find((user: IUserInfo) => user.username === username && user.password === password);
if (!user) {
return null
}
// 设置当前用户
this.currentUser = user;
return user;
},
// 退出登录
logoutUser() {
this.currentUser = null;
},
updateUser(updatedUserInfo: IUserInfo) {
// 如果当前用户不存在,返回
if (!this.currentUser) return;
console.log("currentuser = ", this.currentUser)
// 更新当前用户
this.currentUser = { ...this.currentUser, ...updatedUserInfo };
console.log("currentuser1 = ", this.currentUser)
// 更新 users 数组中的对应用户信息
const userIndex = this.users.findIndex((user: IUserInfo) => user.username === this.currentUser.username);
// 如果找到了对应的用户,更新该用户信息
if (userIndex !== -1) {
// 使用深拷贝来更新 user 数组中的用户信息
this.users[userIndex] = { ...this.users[userIndex], ...updatedUserInfo };
// 更新 users 数组到 localStorage
localStorage.setItem('users', JSON.stringify(this.users));
}
},
// 获取当前用户信息
getCurrentUser() {
return this.currentUser;
},
// 设置管理员登录
setAdmin() {
}
},
persist: true, // 启用持久化
});