1. Install plug-ins
First, you need to install the pinia-plugin-persistedstate plugin. If using npm, you can run the following command:
npm install pinia-plugin-persistedstate
2. Use plug-ins in the Pinia store
1. Import Pinia and plugins
In your JavaScript or TypeScript file (usually the one that creates the Pinia store), first import createPinia and createPersistedState:
import { createPinia } from 'pinia'; import { createPersistedState } from 'pinia-plugin-persistedstate';
2. Create a Pinia instance and apply the plug-in
Create a Pinia instance and use the createPersistedState plugin:
const pinia = createPinia(); (createPersistedState());
3. Use persistence in the store
Suppose you have a simple counter store like this:
import { defineStore } from 'pinia'; export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), actions: { increment() { ++; } }, // Use plug-in configuration options persist: { key: 'my-counter-store',// Custom stored key name storage: localStorage // Can be changed to sessionStorage } });
In this way, when the application is reloaded, the value of count will be restored from the storage (localStorage or sessionStorage) and will be automatically saved to the storage when the state changes.
In Pinia, if you want to persist only a specific value, and other state values do not need to be persisted, you can do this by using the paths option in the persist configuration. paths allows you to specify which state values need to be persisted.
import { defineStore } from 'pinia'; import { createPersistedState } from 'pinia-plugin-persistedstate'; export const useCounterStore = defineStore('counter', { state: () => ({ count: 0, // Assume there are other state values that do not need to be persisted anotherValue: 'some value' }), actions: { increment() { ++; } }, // Use plug-in configuration options persist: { key: 'my-counter-store', // Custom stored key name storage: localStorage, // Can be changed to sessionStorage paths: ['count'] // Only persist count } });
In this example, the paths option in the persist configuration is set to ['count'], which means that only the count state value will be persisted into localStorage. Other state values (such as anotherValue) will not be persisted.
This is the end of this article about the detailed explanation of vue3 pinia to achieve persistence. For more related vue3 pinia persistence content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!