| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- import {defineStore} from "pinia";
- import type User from "@/mode/User";
- import type UserSimple from "@/mode/UserSimple";
- import UserApi from "@/api/UserApi";
- export interface State {
- user: User | null;
- userMap: Map<string, UserSimple>;
- }
- // defineStore 调用后返回一个函数,调用该函数获得 Store 实体
- export const useUserStore = defineStore({
- // id: 必须的,在所有 Store 中唯一
- id: "user_store",
- // state: 返回对象的函数
- state: (): State => ({
- user: null,
- userMap: new Map<string, UserSimple>(),
- }),
- // 开启数据缓存
- persist: {
- enabled: true,
- strategies: [
- {
- key: 'user',
- storage: localStorage,
- paths: ['user']
- }
- ]
- },
- getters: {
- getMapUser: (state) => {
- return (id: string) => {
- return state.userMap.get(id)
- }
- }
- },
- actions: {
- setUser(user: User): void {
- this.user = user;
- },
- getUser(): User | null {
- return this.user;
- },
- getCacheUser(userId:string): UserSimple | undefined {
- return this.userMap?this.userMap.get(userId):undefined;
- },
- storeUser(userId: string,user: UserSimple): void {
- this.userMap.set(userId,user);
- },
- async loadMapUser(id: string) {
- return UserApi.getUser(id).then((res) => {
- if (res.data) {
- this.storeUser(id, res.data)
- }
- })
- }
- },
- });
|