在 Pinia 中实现状态持久化可以借助第三方插件 pinia-plugin-persistedstate
,它能帮助我们将 Pinia store 中的状态保存到本地存储(如 localStorage
、sessionStorage
)或其他存储介质中,在页面刷新或重新打开应用时恢复状态。以下是详细的实现步骤:
1. 安装插件
首先,你需要使用 npm
或者 yarn
来安装 pinia-plugin-persistedstate
插件。
使用 npm 安装
npm install pinia-plugin-persistedstate
使用 yarn 安装
yarn add pinia-plugin-persistedstate
2. 配置插件
在项目中引入并使用该插件,通常在创建 Pinia 实例的文件中进行配置,示例如下:
// store/index.js 或 store/index.ts
import {
createPinia } from 'pinia';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';
const pinia = createPinia();
// 使用插件
pinia.use(piniaPluginPersistedstate);
export default pinia;
3. 在 Store 中启用持久化
在定义具体的 store 时,通过 persist
选项来启用状态持久化功能。可以根据需求设置不同的持久化配置,以下是几种常见的配置方式:
3.1 基本配置
// store/counter.js 或 store/counter.ts
import {
defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
}
},
// 启用持久化
persist: true
});
在上述示例中,将 persist
设置为 true
,表示启用默认的持久化配置,即使用 localStorage
存储状态,存储的键名默认为 store 的 id(这里是 counter
)。
3.2 自定义存储介质
可以通过 storage
选项指定使用 sessionStorage
或其他存储方式。
// store/counter.js 或 store/counter.ts
import {
defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
}
},
persist: {
storage: sessionStorage
}
});
这里将 storage
设置为 sessionStorage
,表示使用会话存储来保存状态。
3.3 自定义存储键名
通过 key
选项可以自定义存储在本地的键名。
// store/counter.js 或 store/counter.ts
import {
defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
}
},
persist: {
key: 'my-custom-counter-key',
storage: localStorage
}
});
在这个例子中,状态将以 my-custom-counter-key
为键名存储在 localStorage
中。
3.4 部分状态持久化
如果只需要对 store 中的部分状态进行持久化,可以使用 paths
选项指定要持久化的状态路径。
// store/user.js 或 store/user.ts
import {
defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
state: () => ({
name: 'John',
age: 30,
tempData: 'temporary'
}),
actions: {
updateName(newName) {
this.name = newName;
}
},
persist: {
paths: ['name', 'age']
}
});
这里只有 name
和 age
状态会被持久化,tempData
状态不会保存到本地。
4. 在组件中使用持久化的 Store
在组件中引入并使用定义好的 store,状态会在页面刷新或重新打开应用时自动恢复。
<template>
<div>
<p>Count: {
{ counterStore.count }}</p>
<button @click="counterStore.increment">Increment</button>
</div>
</template>
<script setup>
import { useCounterStore } from '../store/counter';
const counterStore = useCounterStore();
</script>
通过以上步骤,你就可以在 Pinia 中实现状态持久化,确保应用的重要状态在不同会话之间得以保留。