State
在 Pinia 中,state 被定义为一个返回初始状态的函数。这使得 Pinia 可以同时支持服务端和客户端。
1import {defineStore} from "pinia";
2
3export const useCounterStore = defineStore('counter', {
4 // 为了完整类型推理,推荐使用箭头函数
5 state: () => {
6 return {
7 count: 0
8 }
9 },
10})
访问state
1const store = useCounterStore()
2// 访问
3store.count++
重置state
1const store = useCounterStore()
2// 重置
3store.$reset()
1export const useCounterStore = defineStore('counter', () => {
2 const count = ref(0)
3
4 function $reset() {
5 count.value = 0
6 }
7
8 return { count, $reset }
9})
:::
变更state
变更state的方式有三种:
-
直接修改
-
调用 $patch
方法
-
调用 action
修改
1const store = useCounterStore()
2store.count++
1const store = useCounterStore()
2// 补丁对象
3store.$patch({
4 count: store.count + 1,
5})
6// 函数:适用于复杂场景,如集合的修改
7store.$patch((state) => {
8 state.count++
9})
1const store = useCounterStore()
2store.increment()
:::
替换state
你不能完全替换掉 store 的 state,因为那样会破坏其响应性。但是,你可以 patch 它。
1const store = useCounterStore()
2store.$patch({ count: 24 })
订阅state
可以通过 store 的 $subscribe()
方法侦听 state 及其变化。
1const store = useCounterStore()
2
3store.$subscribe((mutation, state) => {
4 console.log(mutation, state)
5})