Skip to content

状态管理 ​

项目使用 Pinia 进行状态管理,配合 Storage 工具实现持久化。

Store 结构 ​

src/store/
├── index.ts              # 统一导出 + Pinia 初始化
└── modules/
    ├── user.ts           # 用户状态(登录/登出/用户信息)
    └── theme.ts          # 主题状态(明暗切换/主题色)

useUserStore ​

typescript
import { useUserStore } from "@/store"

const userStore = useUserStore()

// 状态
userStore.userInfo          // 用户信息

// 登录
await userStore.login(data)            // 账号密码登录
await userStore.loginBySms(data)       // 短信登录
await userStore.loginByWxMa(code)      // 微信小程序静默登录
await userStore.loginByWxMaPhone(data) // 微信手机号快捷登录
await userStore.bindMobileForWxMa(data)// 绑定手机号

// 扫码登录(PC 端二维码确认)
await userStore.qrScan(token)          // 标记已扫码
await userStore.qrConfirm(token)       // 确认登录
await userStore.qrCancel(token)        // 取消登录

// 用户信息
await userStore.getInfo()              // 获取用户信息
await userStore.logout()               // 登出
await userStore.checkSession()         // 检查会话是否有效
userStore.isUserInfoComplete()         // 用户信息是否完整

useThemeStore ​

typescript
import { useThemeStore } from "@/store"

const themeStore = useThemeStore()

// 状态
themeStore.theme            // 'light' | 'dark'
themeStore.isDark           // 是否暗黑模式
themeStore.currentThemeColor// 当前主题色
themeStore.themeVars        // 主题变量对象(响应式)
themeStore.themeCSSVars     // CSS 变量内联样式字符串,用于动态注入

// 方法
themeStore.toggleTheme()                // 切换明暗
themeStore.setCurrentThemeColor(color)  // 设置主题色
themeStore.setNavigationBarColor()      // 设置原生导航栏颜色
themeStore.initTheme()                  // 初始化主题

持久化 ​

Store 通过 Storage 工具读写 uni.setStorageSync,关键数据的存储 key 定义在 constants/index.ts:

常量值用途
ACCESS_TOKEN_KEYaccess_token访问令牌
REFRESH_TOKEN_KEYrefresh_token刷新令牌
USER_INFO_KEYuser_info用户信息缓存
THEME_MODE_KEYapp-theme主题模式
THEME_COLOR_KEYapp-theme-color主题色
ROLE_ROOTROOT超级管理员角色标识
PERM_ALL*:*:*全部权限标识

Token 由 utils/auth.ts 管理(setAccessToken / clearTokens),Store 登录时调用。

自查清单 ​

  • [ ] Store 按功能模块拆分
  • [ ] 敏感数据通过 Storage 持久化
  • [ ] 不在组件中直接操作 uni.setStorageSync,统一走 Store 或 Storage 工具

基于 MIT 许可发布 · 如需部署协助或二开定制,请查看 支持与合作