Pinia does not provide a built-in persistence solution, but third-party plug-ins can be used to achieve Pinia's persistence.
Here are two ways to achieve Pinia persistence:
1. Use the vuex-persistedstate plugin:
vuex-persistedstate is a Vue.js and Vuex plugin that can persist Vuex state to local storage. Since Pinia is based on Vue 3, the vuex-persistedstate@next version needs to be used.
The method of use is as follows:
Install the plugin:
npm install vuex-persistedstate@next
Use the plugin when Pinia is instantiated:
import createPersistedState from 'vuex-persistedstate';
const pinia = createPinia();
pinia.use(createPersistedState({
// 配置项
}));
Configuration items can set the following options:
key: the key name stored in the local storage, the default is 'vuex'.
storage: Specify the local storage to use, the default is window.localStorage.
reducer: custom state transition function.
filter: A function that selects which state subproperties to cache.
restoreState: A function that restores the state in local storage.
For example, to store Pinia's state in sessionStorage:
import createPersistedState from 'vuex-persistedstate';
const pinia = createPinia();
pinia.use(createPersistedState({
storage: window.sessionStorage,
key: 'pinia',
}));
2. Customize the plug-in to achieve persistence:
You can write a plug-in to achieve Pinia persistence, for example, store the Pinia state in localStorage:
import { createPinia } from 'pinia';
const pinia = createPinia();
pinia.use({
// 安装插件时调用
install(app) {
const storageKey = 'pinia-state';
// 从本地存储中读取状态
const storedState = localStorage.getItem(storageKey);
if (storedState) {
// 将本地存储的状态转换为 JSON
const parsedState = JSON.parse(storedState);
// 恢复存储的状态
pinia.state.value = parsedState;
}
// 监听 Pinia 状态的变化并将其保存到本地存储
pinia.state.subscribe(newState => {
localStorage.setItem(storageKey, JSON.stringify(newState));
});
},
});
In this way, the state persistence of Pinia can be realized. It should be noted that for large applications, the custom implementation of the plug-in may become complicated, so it is recommended to use a third-party library to implement Pinia's persistence.