SoFunction
Updated on 2025-04-05

About Pinia State Persistence Issues

Pinia state persistence

In vue3, Pinia is commonly used instead of Vuex for state management. Here is the official website of Pinia. If you are interested, you can learn about it.Pinia🍍

Other processes have been omitted. Today, a simplest Pinia persistence plug-in is implemented in vue3, and it may be further encapsulated later.

//   FilePath <  @/ >

import { createApp, toRaw } from 'vue'
import App from './'
// Introduce piniaimport { createPinia, PiniaPluginContext } from "pinia";

const app = createApp(App)

type Options = {
    key?: string
}
// Default keyconst __piniaKey__: string = 'Ocean'
// The function responsible for storageconst setStorage = (key: string, value: any) => {
    // Turn the object into string and save it into localStorage    (key, (value))
}
// Function responsible for taking valuesconst getStorage = (key: string) => {
    // Get the corresponding value in localStorage according to the key    return (key) ? ((key) as string) : {}
}
// Pinia persistence pluginconst piniaPlugin = (options: Options) => {
    return (context: PiniaPluginContext) => {
        const { store } = context
        const data = getStorage(`${options?.key ?? __piniaKey__}-${store.$id}`)
        (data);
        
        store.$subscribe(() => {
            // store.$state is a proxy object to be converted into the original object through toRaw()            setStorage(`${options?.key ?? __piniaKey__}-${store.$id}`,toRaw(store.$state))
        })
        return {
            ...data
        }
    }
}
// Create a Pinia instanceconst store = createPinia()
// Register plugin(piniaPlugin({
    key: 'pinia'
}))

(store)
('#app')

Pinia data persistence processing

1. Download the plugin pinia-plugin-persist

Next

import { createPinia } from 'pinia'
//pinia persistence pluginimport piniaPluginPersist from 'pinia-plugin-persist'
const store = createPinia()
(piniaPluginPersist)
export default store

Add configuration items to the written file. The default is sessionStorage

  persist: {
        enabled: true,
        strategies: [
            {
                key: 'user',
                storage: localStorage,
                path:[] //You can choose to save the fields  The rest are not saved            }
        ]
    }

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.