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)// 绑定手机号
await userStore.getInfo()             // 获取用户信息
await userStore.logout()              // 登出
userStore.isUserInfoComplete()        // 用户信息是否完整

useThemeStore

typescript
import { useThemeStore } from "@/store"

const themeStore = useThemeStore()

// 状态
themeStore.theme            // 'light' | 'dark'
themeStore.isDark           // 是否暗黑模式
themeStore.currentThemeColor// 当前主题色
themeStore.themeVars        // 主题变量(响应式)

// 方法
themeStore.toggleTheme()                // 切换明暗
themeStore.setCurrentThemeColor(color)  // 设置主题色
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主题色

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

自查清单

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

基于 MIT 许可发布 · 由 ❤️ 和 ☕ 驱动 · 支持作者