组合式 api 中定义 setup store 需用 definestore 传入函数,显式 return ref(state)、computed(getter)、普通函数(action)以暴露接口;未 return 的变量不可访问,且 typescript 下需注意类型标注。

在组合式 API 中定义 Setup 式 Store,核心是用 defineStore 传入一个函数,该函数内部使用 ref、computed 和普通函数来分别对应 state、getter 和 action,并统一 return 出去。
明确返回所有需暴露的属性
Setup Store 不像 Options Store 那样自动识别 state、getters、actions 字段,而是靠你显式 return 的内容来决定哪些可被外部访问。任何没 return 的响应式变量(比如只声明了 const hidden = ref(0) 却没放进 return 对象),组件就拿不到。
- 必须 return
ref()类型变量——它们成为可读写的 state - 必须 return
computed()类型变量——它们成为只读的 getter - 必须 return 普通函数——它们成为可调用的 action
- 不能只 return 部分字段;例如只 return
count和increment,那name或doubleCount就不可见
写法示例:一个完整可运行的 counter store
以下代码放在 stores/counter.ts 中即可直接导入使用:
import { defineStore, ref, computed } from 'pinia'
<p>export const useCounterStore = defineStore('counter', () => {
// ✅ state:用 ref 声明
const count = ref(0)
const name = ref('Pinia')</p><p>// ✅ getter:用 computed 声明
const doubleCount = computed(() => count.value * 2)
const welcomeMessage = computed(() => <code>Hello, ${name.value}! You have ${doubleCount.value} items.</code>)</p><p>// ✅ action:定义函数
const increment = () => count.value++
const decrement = () => count.value--
const asyncIncrement = async () => {
await new Promise(resolve => setTimeout(resolve, 1000))
count.value += 10
}</p><p>// ✅ 必须 return 所有要暴露的内容
return {
count,
name,
doubleCount,
welcomeMessage,
increment,
decrement,
asyncIncrement
}
})
</p>
注意类型与 TypeScript 支持
Pinia 对 TypeScript 友好,但需确保项目开启 strict 或至少 noImplicitThis。多数类型能自动推断,但以下情况建议手动标注:
- 空数组初始值:如
items: [] as string[] - 可能为 null 的对象:如
user: null as User | null - getter 中使用
this(如访问其他 getter)时,必须写明返回类型,例如doublePlusOne(): number { return this.doubleCount + 1 }
在组件中使用它
在 <script setup></script> 中直接调用 store 函数,拿到实例后即可读写 state、访问 getter、执行 action:
<script setup>
import { useCounterStore } from '@/stores/counter'
<p>const store = useCounterStore()
</script><p><template><div>
<p>Count: {{ store.count }}</p>
<p>Double: {{ store.doubleCount }}</p>
<button>+1</button>
<button>+10 async</button>
</div>
</template></p>
无需 computed 包裹 state 或 getter,也不用 mapState 等映射辅助函数——直接访问即可,响应性由 Pinia 自动维护。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










