persist.ts 872 B

1234567891011121314151617181920212223242526272829
  1. import type { PiniaPluginContext } from 'pinia'
  2. function persist({ store }: PiniaPluginContext, excludedIds: string[]) {
  3. // 检查当前store的id是否在排除列表中
  4. const isExcluded = excludedIds.includes(store.$id)
  5. // 如果当前store的id在排除列表中,则不进行持久化
  6. if (isExcluded) {
  7. return
  8. }
  9. // 暂存State
  10. let persistState = CommonUtil.deepClone(store.$state)
  11. // 从缓存中读取
  12. const storageState = uni.getStorageSync(store.$id)
  13. if (storageState) {
  14. persistState = storageState
  15. }
  16. store.$state = persistState
  17. store.$subscribe(() => {
  18. // 在存储变化的时候将store缓存
  19. uni.setStorageSync(store.$id, CommonUtil.deepClone(store.$state))
  20. })
  21. }
  22. export function persistPlugin(context: PiniaPluginContext) {
  23. // 调用persist函数,并传入排除列表
  24. persist(context, ['confirmOrder'])
  25. }