Skip to content

9.6 状态管理(Pinia) ​

概述

前端使用 Pinia 进行全局状态管理,核心 Store 包含用户信息、动态路由、项目配置等。

Store 清单 ​

Store文件说明
userStorestore/modules/user.tsToken / 用户信息 / 权限列表 / 登录登出
asyncRouteStorestore/modules/asyncRoute.ts动态路由 / keep-alive 缓存
projectSettingStorestore/modules/projectSetting.ts项目配置
ossConfigStorestore/modules/ossConfig.ts云存储配置
designSettingStorestore/modules/designSetting.ts主题设计
lockscreenStorestore/modules/lockscreen.ts锁屏
tabsViewStorestore/modules/tabsView.ts标签页

userStore 核心代码 ​

typescript
// src/store/modules/user.ts

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => ({
    token: Storage.get(ACCESS_TOKEN, ''),
    username: '',
    avatar: '',
    permissions: [],
    info: Storage.get(CURRENT_USER, {}),
  }),
  actions: {
    // 登录
    async login(userInfo) {
      const response = await login(userInfo);
      if (response.code === 0) {
        storage.set(ACCESS_TOKEN, response.data.access_token);
        this.setToken(response.data.access_token);
      }
      return response;
    },

    // 获取用户信息
    async GetInfo() {
      const res = await getUserInfo();
      this.setPermissions(res.permissions);
      this.setUserInfo(res);
      this.setAvatar(res.avatar);
      return res;
    },

    // 登出
    async logout() {
      await logout();
      this.setPermissions([]);
      this.setUserInfo('');
      storage.remove(ACCESS_TOKEN);
      storage.remove(CURRENT_USER);
    },
  },
});

在组件中使用 ​

Store 使用方式

  • 在 setup 中:const userStore = useUserStore()
  • 在 setup 外:const userStore = useUserStoreWidthOut()
typescript
import { useUserStore } from '@/store/modules/user';

const userStore = useUserStore();

// 获取用户信息
const username = userStore.username;
const permissions = userStore.permissions;

// 登录
await userStore.login({ username: 'admin', password: '123456' });

// 登出
await userStore.logout();

小蚂蚁云团队 · 提供技术支持