import { PiniaPluginContext } from "pinia";
export function persistedstate(context: PiniaPluginContext) {
const currentState = JSON.parse(localStorage.getItem(context.store.$id) || "{}")
context.store.$patch(currentState)
//第一个时当前修改store的上下文,第二个是当前修改的状态
context.store.$subscribe((_store,state) =>{
localStorage.setItem(_store.storeId,JSON.stringify(state))
},{
//组件卸载依赖还在
detached:true
})
}
在这个插件函数中,我们首先通过`localStorage`获取存储在其中的Store状态,然后使用`$patch`方法将获取的状态应用到当前的Store实例中。接下来,我们使用`$subscribe`方法订阅Store的状态变化,当状态发生变化时,我们将更新后的状态存储回`localStorage`中。
请注意,这仅仅是一个基本的实现示例,需要根据自己的需求进行适当的调整和扩展。同时,在使用`localStorage`存储数据时,确保遵守相关的安全性和隐私规定。