Pinia 是一个用于 Vue 的状态治理库,相似 Vuex, 是 Vue 的另一种状态治理计划。如果你现在使用 vue3 开发项目,那么推荐你使用 Pinia 开发。

Pinia的优点

1、完整的 TypeScript 支持:与在 Vuex 中添加 TypeScript 相比,添加 TypeScript 更容易。

2、极其轻巧(体积约 1KB)

3、store 的 action 被调度为常规的函数调用,而不是使用 dispatch 方法,这在 Vuex 中很常见。

4、支持多个Store,Pinia 不支持嵌套存储。相反,它允许你根据需要创建 store。但是,store 仍然可以通过在另一个 store 中导入和使用 store 来隐式嵌套。

5、支持 Vue devtools、SSR 和 webpack 代码拆分

快速开始

npm install pinia

创建一个 pinia 作为 root store 添加到 app 中。

import { createApp } from 'vue'
import { createPinia } from 'pinia'

const app = createApp({})
app.use(createPinia())

开始定义 store,注意:没有 mutations 选项了。

export const useStore = defineStore('main', {
state: () => ({
counter: 0,
}),
getters: {
doubleCount: (state) => state.counter * 2,
},
actions: {
increment() {
this.counter++
},
randomizeCounter() {
this.counter = Math.round(100 * Math.random())
},
},
})

在组件中使用 store 。

<template>
<div>
<!-- 注意不是 store.state.count -->
{{store.count}}
</div>
</template>

<script>
import { useStore } from '@/stores/counter'

export default {
setup() {
const store = useStore()

return {
// 可以返回 store 在模板中使用
store,
}
},
}
</script>

同样也支持之前的辅助函数。可以使用 mapState 来映射我们 store 中的 state 和 getter,注意:没有 mapMutations 和 mapGetters 了。也可以使用 mapActions 来映射 action 函数。

import { mapState } from 'pinia'

export default {
computed: {
..mapState(useStore, ['counter', 'doubleCount'])
},
methods: {
...mapActions(useStore, ['increment'])
...mapActions(useStore, { myOwnName: 'randomizeCounter' }),
},
}

修改状态有很多种方式

import { useCounterStore } from '@/stores/counter'

export default {
setup() {
const counter = useCounterStore()
// 默认支持手动直接修改
counter.count++
// 使用内部提供的 $patch 方法自动修改值,而且可以修改多个 key 值,推荐
counter.$patch({ count: counter.count + 1 })
// 或者使用 action 代替
counter.increment();
},
}

注意,Pinia 没有 mutation 了,只有 action 部分。

并且 state 必须是函数形式。并且可以重置恢复到之前的初始状态

const store = useStore()

store.$reset()

可以通过将 store 的 $state 属性设置为新对象,可以替换 store 的整个状态:

store.$state = { counter: 666, name: 'Paimon' }

Pinia 相比 Vuex 更加简略,而且 Pinia 能够自在扩大。

Pinia 是合乎直觉的状态治理形式,让使用者回到了模块导入导出的原始状态,使状态的起源更加清晰可见。

Pinia 的应用感触相似于 Recoil,但没有那么多的概念和 API,主体十分精简,极易上手(Recoil 是 Facebook 官网出品的用于 React 状态治理库,应用 React Hooks 治理状态)。

而且 Pinia 适用于 Vue 2 和 Vue 3,并且不要求您使用 composition API。