pinia setup 风格 store 用 definestore 返回函数,内用 ref 定义 state、computed 定义 getter、普通函数定义 action;ref 必须 return 才暴露,computed 仅读取,action 可异步;跨 store 调用需在 getter/action 内进行以避免循环依赖。

Pinia 结合组合式 API 定义 Setup 风格的 Store,核心是用 defineStore 传入一个函数,在函数内部使用 ref、computed 和普通函数分别定义 state、getter 和 action,并显式 return 所有需要暴露的成员。
用 ref 声明可读写的状态
所有需被组件访问的响应式数据,必须用 ref() 创建并返回。它们会自动成为 store 的 state 字段:
-
const count = ref(0)→ 组件中可通过store.count读写 -
const items = ref([] as string[])→ TypeScript 下建议显式标注类型,尤其空数组或复杂结构 - 未 return 的 ref(如
const hidden = ref(0))在外部完全不可见
用 computed 声明只读的计算属性
所有需缓存、依赖其他响应式值的派生状态,用 computed() 创建并返回。它们会作为 getter 暴露:
-
const doubleCount = computed(() => count.value * 2)→ 组件中通过store.doubleCount访问,不可赋值 - 可嵌套调用其他 store 的 getter 或 action(见下文“跨 store 使用”)
- 避免在 computed 中执行副作用(如发起请求),应放在 action 里
用普通函数定义可调用的行为
同步或异步逻辑统一写成函数并返回,它们就是 store 的 actions:
-
const increment = () => count.value++→ 组件中调用store.increment() -
const loadUser = async () => { const data = await api.getUser(); user.value = data }→ 支持 await,this 不再需要,直接操作 ref - 函数内可自由使用 watch、onMounted 等组合式 API(仅限 Setup Store)
跨 store 使用要避开初始化循环
一个 store 需要另一个 store 时,不能在顶层直接调用 useXStore(),否则触发依赖死锁:
- ❌ 错误:在
useCartStore的顶层写const user = useUserStore() - ✅ 正确:在 getter 或 action 内部调用,例如:
const summary = computed(() => `Hi ${useUserStore().name}`)
或const checkout = () => { const user = useUserStore(); return apiPay(user.id) } - 也可提前导入并在 setup 函数顶部调用,只要不形成双向顶层依赖
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










