Pinia在组合式API中使用分三步:安装注册根仓库、定义模块化store、组件中调用useStore获取实例;支持跨组件状态共享与自动响应更新。

Pinia 在组合式 API 中的引入和使用非常直接,核心是三步:安装并注册根仓库、定义模块化 store、在组件中调用 useStore 函数获取实例。
安装并注册 Pinia 根仓库
先通过包管理器安装:
- npm install pinia 或 yarn add pinia
在 src/store/index.ts(或 .js)中创建根仓库实例:
import { createPinia } from 'pinia'
export const store = createPinia()
然后在项目入口文件 main.ts 中注册:
import { createApp } from 'vue'
import { store } from './store'
import App from './App.vue'
<p>const app = createApp(App)
app.use(store) // 注册为插件
app.mount('#app')
定义组合式写法的 store 模块
在 src/store/modules/counter.ts 中使用函数式 defineStore:
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
<p>export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const double = computed(() => count.value * 2)</p><p>function increment() {
count.value++
}</p><p>function reset() {
count.value = 0
}</p><p>return {
count,
double,
increment,
reset
}
})
注意:返回的对象中所有属性和方法都会自动响应式,无需额外处理。
在 setup 组件中使用 store
在 <script setup></script> 中直接导入并调用:
<template>
<div>
<p>当前数量:{{ counterStore.count }}</p>
<p>两倍值:{{ counterStore.double }}</p>
<button @click="counterStore.increment">+1</button>
<button @click="counterStore.reset">重置</button>
</div>
</template>
<p><script setup lang="ts">
import { useCounterStore } from '@/store/modules/counter'</p><p>const counterStore = useCounterStore()
</script>
useCounterStore() 返回的是一个响应式 store 实例,可直接读取 state、调用 action、访问 getter。
跨组件共享与响应更新
同一个 store 实例被多个组件调用时,状态是全局共享的。例如 A 组件调用 increment() 后,B 组件中 counterStore.count 会自动更新,不需要 emit 或 props 传递。
所有 ref、computed、reactive 定义的内容都天然接入 Vue 响应系统,无需手动 watch 或 onMounted 订阅。


















