状态管理
约 240 字小于 1 分钟
Vue
2025-10-10
Pinia 是 Vue3 官方推荐的状态管理库。
与 Vuex 相比,Pinia 不仅提供了一个更简单的 API,也提供了符合组合式 API 风格的 API,最重要的是, 搭配 TypeScript 一起使用时有非常可靠的类型推断支持。
安装
npm install pinia
创建一个 pinia 实例 (根 store) 并将其传递给应用:
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')
语法
Pinia 支持两种写法 - 选项式(options)与 组合式(setup)。
Option Store:
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0, name: 'Eduardo' }),
getters: {
doubleCount: (state) => state.count * 2,
},
actions: {
increment() {
this.count++
},
},
})
Setup Store:
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const name = ref('Eduardo')
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, name, doubleCount, increment }
})
在 Setup Store 中,ref()
就是 state
属性,computed()
就是 getters
,function()
就是 actions
。
持久化
持久化数据,需要使用 Pinia Persistedstate 插件。