wanshenmean
12 小时以前 f288ccc545f8cc32bc922c96dfb3cab9a1f92ec6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
 
interface UserInfo {
  token: string;
  userName: string;
  userTrueName: string;
  img: string;
}
 
export const useUserStore = defineStore('user', () => {
  const userInfo = ref<UserInfo | null>(null);
  const token = ref<string>('');
  const isLogin = computed(() => !!token.value);
 
  function init() {
    const stored = localStorage.getItem('user');
    if (stored) {
      try {
        const info = JSON.parse(stored) as UserInfo;
        userInfo.value = info;
        token.value = info?.token || '';
      } catch {
        token.value = '';
      }
    }
  }
 
  function setUserInfo(info: UserInfo) {
    userInfo.value = info;
    token.value = info?.token || '';
    localStorage.setItem('user', JSON.stringify(info));
  }
 
  function clearUserInfo() {
    userInfo.value = null;
    token.value = '';
    localStorage.removeItem('user');
  }
 
  init();
  return { userInfo, token, isLogin, setUserInfo, clearUserInfo };
});