签入版本
This commit is contained in:
@@ -19,7 +19,9 @@
|
||||
## userStore 核心代码
|
||||
|
||||
```typescript
|
||||
// src/store/modules/user.ts
|
||||
// ui/src/store/modules/user.ts
|
||||
import { ACCESS_TOKEN, CURRENT_USER, IS_LOCKSCREEN } from '@/store/mutation-types';
|
||||
import { ResultEnum } from '@/enums/httpEnum';
|
||||
|
||||
export const useUserStore = defineStore({
|
||||
id: 'app-user',
|
||||
@@ -31,37 +33,45 @@ export const useUserStore = defineStore({
|
||||
info: Storage.get(CURRENT_USER, {}),
|
||||
}),
|
||||
actions: {
|
||||
// 登录
|
||||
// 登录(key/code 为验证码参数;响应字段为 snake_case 的 access_token,见 8.6)
|
||||
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);
|
||||
const { code, data } = response;
|
||||
if (code === ResultEnum.SUCCESS) {
|
||||
const ex = 7 * 24 * 60 * 60 * 1000;
|
||||
storage.set(ACCESS_TOKEN, data.access_token, ex); // 仅存 access_token
|
||||
storage.set(IS_LOCKSCREEN, false);
|
||||
this.setToken(data.access_token);
|
||||
}
|
||||
return response;
|
||||
},
|
||||
|
||||
// 获取用户信息
|
||||
// 获取用户信息(含 roles / permissions / city)
|
||||
async GetInfo() {
|
||||
const res = await getUserInfo();
|
||||
const res = await getUserInfo(); // GET /api/index/getUser
|
||||
this.setPermissions(res.permissions);
|
||||
this.setUserInfo(res);
|
||||
this.setAvatar(res.avatar);
|
||||
return res;
|
||||
},
|
||||
|
||||
// 登出
|
||||
// 登出(后端同时吊销 refresh_token)
|
||||
async logout() {
|
||||
await logout();
|
||||
this.setPermissions([]);
|
||||
this.setUserInfo('');
|
||||
storage.remove(ACCESS_TOKEN);
|
||||
storage.remove(CURRENT_USER);
|
||||
storage.clear();
|
||||
},
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
:::tip 权限与后端一致
|
||||
`GetInfo` 拿到的 `permissions` 与 `Authenticate` 中间件鉴权用的是同一份数据(复用 `JwtService::getUserPermissions` 的 Redis 缓存)——超管为 `['*:*:*']`,普通用户为角色关联的 `menu.permission` 列表。
|
||||
:::
|
||||
|
||||
## 在组件中使用
|
||||
|
||||
:::tip Store 使用方式
|
||||
@@ -79,8 +89,18 @@ const username = userStore.username;
|
||||
const permissions = userStore.permissions;
|
||||
|
||||
// 登录
|
||||
await userStore.login({ username: 'admin', password: '123456' });
|
||||
await userStore.login({ username: 'admin', password: '123456', key, code });
|
||||
|
||||
// 登出
|
||||
await userStore.logout();
|
||||
```
|
||||
```
|
||||
|
||||
## asyncRouteStore(动态路由)
|
||||
|
||||
| 状态/方法 | 说明 |
|
||||
|------|------|
|
||||
| `getIsDynamicAddedRoute` | 动态路由是否已加载(守卫据此跳过重复生成) |
|
||||
| `generateRoutes(userInfo)` | 调用 `/api/index/getMenus` 生成路由表 |
|
||||
| `keepAliveComponents` | 页面级缓存组件名列表(标签页切换保留状态) |
|
||||
|
||||
(生成细节见 [9.5 路由与动态菜单](/zh/frontend/router.html)。)
|
||||
|
||||
Reference in New Issue
Block a user