SoFunction
Updated on 2025-04-04

In-depth understanding of Vue Pinia persistent storage secondary packaging

What is Pinia

Piniais a new generation of state management library redesigned by official members in 2019, similar to Vuex. I won’t introduce it more here. For specific usage methods, please refer to the Pinia homepage.

Let's study the persistent storage plug-in developed based on Pinia

What is persistent storage

Simply put, the browser cache and the Store are synchronized with each other; when we use regular Store storage, we will encounter refreshing the page status library and reset, which makes us very troubled;
Usually when we encounter this problem, it is easy for us to think of it.sessionStorageorlocalStorageTo store the corresponding data, when there are too many storage stores, it will be troublesome. You need to write a lot of waste code, which is not easy to read and not beautiful.

Is there a better way?pinia-plugin-persist solves this problem very well; but in actual use, I found an inconvenient point. The plug-in is stored as a module, and a store is a module. Sometimes we need to store one by one. For example, when logging in, we only need to store a userInfo field; in order to deal with similar situations, it has been upgraded and transformed based on pinia-plugin-persist.

Related source code

interface PersistStrategy {
  key?: string
  storage?: Storage
  paths?: string[]
}
interface PersistOptions {
  enabled: true
  strategies?: PersistStrategy[]
}
declare module 'pinia' {
  interface DefineStoreOptionsBase<S, Store> {
    persist?: PersistOptions
  }
}

export { PersistOptions, PersistStrategy }

import { PiniaPluginContext } from 'pinia'
import { PersistStrategy } from '../pinia-persist'

type Store = PiniaPluginContext['store']
type PartialState = Partial&lt;Store['$state']&gt;

// Update local cacheexport const updateStorage = (strategy: PersistStrategy, store: Store) =&gt; {
  const storage = strategy?.storage || sessionStorage
  const paths = strategy?.paths || []
  if () {
    // Determine whether to cache according to the module    const state = ((obj, key) =&gt; {
      obj[key] = store.$state[key]
      return obj
    }, {} as PartialState)
    (, (state))
  } else {
    // Single cache    ((key) =&gt; {
      const state = store.$state[key]
      (key, (state))
    })
  }
}

export default ({ options, store }: PiniaPluginContext): void =&gt; {
  // Determine whether the plug-in function is enabled  if (?.enabled) {
    // Default policy instance    const defaultStrategy = [
      {
        key: store.$id,
        storage: sessionStorage,
        paths: []
      }
    ]

    const strategies = ?.strategies?.length ? ?.strategies : defaultStrategy

    ((strategy) =&gt; {
      const storage = strategy?.storage || sessionStorage
      const paths = strategy?.paths || []
      if () {
        const result = ()
        result &amp;&amp; store.$patch((result))
      } else {
        ((key) =&gt; {
          const result = (key)
          if (result) {
            const obj: { [key: string]: any } = {}
            obj[key] = (result)
            // Synchronously update store data            store.$patch(obj)
          }
        })
      }
    })

    // Listen to state changes and update storage synchronously    store.$subscribe(() =&gt; {
      ((strategy) =&gt; {
        updateStorage(strategy, store)
      })
    })
  }
}

Introduced

store/

import { createPinia } from 'pinia'
import piniaStorePersist from '@/plugins/pinia-persist/pinia-store-persist'

const store = createPinia().use(piniaStorePersist)

export default store

use

export const CommonStore = defineStore('common', {
  //...
  persist: {
    enabled: true,
    strategies: [
      {
        storage: localStorage,
        paths: ['userInfo']
      }
    ]
  }
})

This is the end of this article about in-depth understanding of Vue Pinia persistent storage secondary packaging. For more related Vue Pinia storage content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!