在最新的 Vue 官方文档中,核心库的地址已经指向了Pinia,这表明已经把 Pinia 当做 Vue3.x 的官方状态管理库了。下面来探索下 Pinia 的使用方式。
基础
在 Pinia 的首页文档上介绍了最基础的使用方式:
// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => {
return { count: 0 }
},
// could also be defined as
// state: () => ({ count: 0 })
actions: {
increment() {
this.count++
},
},
})
注意上图的代码,里面用了this.count++
在我第一次看到的时候,就觉得不舒服,因为整个项目已经是 Composition 的写法了,已经不再使用this
了,不明白官方的推荐写法为什么是这样的。
所以我去提了个 issue:use state instead of this in actions
作者回复了:
There are two reasons actions do not take any parameters by default:
- Allow the user to define any parameters as they want
- Type support: passing the state wouldn't be enough in actions, we would need to pass the store but then actions wouldn't be automatically typed because of a limitation in TS
This is not stated in docs because it's an implementation detail and would confuse most users.
解决方案
看完之后我感觉并没有说清楚,后来自己又在文档首页发现了下面这样的写法:
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
function increment() {
count.value++
}
return { count, increment }
})
感觉还不错,使用最新的 Vue.js devtools
调试,发现这种也会有一个 state ,调用方法的时候也会有 pinia 的 action 记录产生,调试没问题