pinia本身提供了一個(gè)reset方法,可以重置store
store.$reset()
但是在項(xiàng)目中應(yīng)用setup語(yǔ)法的時(shí)候會(huì)拋出錯(cuò)誤,網(wǎng)上找了方法解決了問(wèn)題,現(xiàn)整理一下
分析原因
根據(jù)報(bào)錯(cuò)可以理解,因?yàn)閟etup寫(xiě)法中 storer 的 $reset 方法未實(shí)現(xiàn),那順著這個(gè)思路就需要自己手動(dòng)實(shí)現(xiàn)一下
實(shí)現(xiàn)方式
pinia支持自定義插件,因此通過(guò)插件將自定義的$reset方法寫(xiě)入
const store = createPinia();
// 手動(dòng)重置
const resetPlugin = (plugin) => {
const { store, options } = plugin;
// 備份初始值
const initialState = JSON.parse(JSON.stringify(store.$state));
// 重置
store.$reset = () => {
store.$state = JSON.parse(JSON.stringify(initialState));
};
};
store.use(resetPlugin);
其它問(wèn)題
1、有的文章推薦使用store.$patch()方法實(shí)現(xiàn),實(shí)際項(xiàng)目中有個(gè)別值未重置,原因暫時(shí)未知,因此目前還是用上述代碼實(shí)現(xiàn)
2、持久化
項(xiàng)目中使用了pinia-plugin-persist進(jìn)行部分字段持久化,遇到pinia重置了但localStorage未重置,排查了好久才解決,真相令人暖心:只需要將pinia-plugin-persist在resetPlugin之后掛載就可以了
store.use(resetPlugin);
store.use(piniaPluginPersist);