86 lines
2.2 KiB
Markdown
86 lines
2.2 KiB
Markdown
# 9.6 状态管理(Pinia)
|
||
|
||
:::tip 概述
|
||
前端使用 Pinia 进行全局状态管理,核心 Store 包含用户信息、动态路由、项目配置等。
|
||
:::
|
||
|
||
## Store 清单
|
||
|
||
| Store | 文件 | 说明 |
|
||
|-------|------|------|
|
||
| userStore | `store/modules/user.ts` | Token / 用户信息 / 权限列表 / 登录登出 |
|
||
| asyncRouteStore | `store/modules/asyncRoute.ts` | 动态路由 / keep-alive 缓存 |
|
||
| projectSettingStore | `store/modules/projectSetting.ts` | 项目配置 |
|
||
| ossConfigStore | `store/modules/ossConfig.ts` | 云存储配置 |
|
||
| designSettingStore | `store/modules/designSetting.ts` | 主题设计 |
|
||
| lockscreenStore | `store/modules/lockscreen.ts` | 锁屏 |
|
||
| tabsViewStore | `store/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);
|
||
},
|
||
},
|
||
});
|
||
```
|
||
|
||
## 在组件中使用
|
||
|
||
:::tip 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();
|
||
``` |