什么是 State
在 Pinia 中,状态被定义为返回初始状态的函数,可以通过 store 实例访问状态来直接读取和写入状态
重置状态
// 通过调用 store 上的 $reset() 方法将状态重置到其初始值
// 实例化 store
const store = useStore();
// 重置
store.$reset();
上一个笔记的基本使用 store ,都是在 setup() 钩子中使用,优点很明显,简单方便
但是如果不使用 Composition API,并且使用的是 computed、methods。则可以使用 mapState() 帮助器将状态属性映射为只读计算属性
import { mapState } from 'pinia';
import { useCounterStore } from '../stores/counterStore';
export default {
computed:{
// 允许访问组件内部的 this.cunter,与从 store.counter 读取相同
...mapState('useCounterStore',{
myOwnName:'counter',
// 可以是一个访问 store 的函数
double: store => store.counter * 2
// 函数中可以正常读取 this
magicValue(store) {
return store.counter + this.counter + this.double
}
})
}
}
如果希望能够写入这些状态的属性,可以使用 mapWritableState() 代替
import { mapWritableState } from 'pinia'
import { useCounterStore } from '../stores/counterStore'
export default {
computed: {
// 允许访问组件内的 this.counter 并允许设置它与从 store.counter 读取相同
...mapWritableState(useCounterStore, ['counter'])
// 与上面相同,但将其注册为 this.myOwnName
...mapWritableState(useCounterStore, {
myOwnName: 'counter',
}),
},
}
改变状态
// 第一种改变状态的方法
const clickHandle=()=>{
store.count++;
store.text=store.count%2!==0?'hello! pinia':'pinia'
}
// 第二种方法 $patch
const patchClickHandle=()=>{
store.$patch({
count:store.count+2,
text:store.text==='pinia'?'hello! pinia':'pinia'
})
}
// 第三种方法 $patch 传递函数
const patchMethodClickHandle=()=>{
store.$patch((state)=>{
store.count++;
store.text=store.count%2!==0?'hello! pinia':'pinia'
})
}
// 第四种方法 actions
// store/index.ts
actions:{
// 不是箭头函数,普通函数
changeState(){
this.count++;
this.text=this.count%2!==0?'hello! pinia':'pinia'
}
}
const actionClickHandle=()=>{
store.changeState()
}
替换 state
可以通过将其 $state 属性设置为新对象来替换 Store 的整个状态:
store.$state = { name:'Y' }
还可以通过更改 pinia 实例的 state 来替换应用程序的整个状态,这在 SSR for hydration 期间使用
pinia.state.value = {}
订阅状态
可以通过 store 的 $subscribe() 方法查看状态及其变化。与常规的 watch() 相比,使用 $subscribe() 的优点是 subscriptions 只会在 patches 之后触发一次
// 默认情况下,state subscriptions 绑定到添加它们的组件(如果 store 位于组件的 setup() 中)。
// 意思是,当组件被卸载时,它们将被自动删除。 如果要在卸载组件后保留它们,请将 { detached: true } 作为第二个参数传递给 detach 当前组件的 state subscription:
export default {
setup() {
const someStore = useSomeStore()
// 此订阅将在组件卸载后保留
someStore.$subscribe(callback, { detached: true })
// ...
},
}
在 pinia 实例上查看整个状态
watch(
pinia.state,
(state) => {
// 每当它发生变化时,将整个状态持久化到本地存储
localStorage.setItem('piniaState', JSON.stringify(state))
},
{ deep: true }
)