全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-06-04 7 分钟 ✍️ juanwangdev

类型化的 Store 模块

类型化的 Store 模块是 Pinia 学习中的单个核心知识点,下面直接说明用法。

定义

类型化的 Store 模块是 Pinia 使用中的一个独立知识点,核心作用是:将Store定义与类型定义分离到不同文件,掌握类型导入导出最佳实践。

语法

类型语法重点是给 state、action 参数和返回值提供明确约束。

TypeScript
interface UserState {
  id: number
  name: string
  roles: string[]
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({ id: 0, name: '', roles: [] }),
  actions: { setName(name: string) { this.name = name } }
})

示例

TypeScript
interface UserState {
  id: number
  name: string
  roles: string[]
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({ id: 0, name: '', roles: [] }),
  actions: { setName(name: string) { this.name = name } }
})

注意事项

复杂状态不要依赖隐式 any,优先声明接口或类型别名。

要点总结

  • 类型化的 Store 模块 只解决当前知识点对应的问题。
  • 优先使用 Pinia 官方 API,避免引入多余封装。
  • 示例代码应保持 Store 简洁、职责清晰。

📝 发现内容有误?点击此处直接编辑

← 上一篇 显式类型注解
下一篇 → 类型安全的 Store 设计
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库