在实际开发中,我们通常需要对状态进行持久化或缓存,以便在应用程序重新加载或离线时仍然能够访问数据。在 Pinia 中,我们可以使用插件来实现状态的持久化和数据缓存。
Pinia 提供了一个名为pinia-plugin-persist
的插件,可以用来实现状态的持久化。该插件会将状态存储在本地存储中,以便在应用程序重新加载时恢复状态。以下是使用该插件的步骤:
# npm
npm install pinia-plugin-persist
# yarn
yarn add pinia-plugin-persist
# pnpm
pnpm add pinia-plugin-persist
import { createApp } from "vue";
import { createPinia } from "pinia";
import piniaPersist from "pinia-plugin-persist";
import App from "./App.vue";
import "@/assets/main.css";
import "@/assets/index.scss";
const pinia = createPinia();
pinia.use(piniaPersist);
createApp(App)
.use(pinia)
.use(router)
.mount("#app");
// tsconfig.json
{
"compilerOptions": {
"types": [
"pinia-plugin-persist"
]
},
}
import { ref, computed } from "vue";
import { defineStore } from "pinia";
export const useCounterStore = defineStore(
"counter",
() => {
const count = ref(1);
const total = ref(10);
const doubleCount = computed(() => count.value * 2);
function increment() {
count.value++;
}
function decrement() {
count.value--;
}
return { count, total, doubleCount, increment, decrement };
},
{
persist: {
enabled: true,
},
}
);
开启enabled
之后,默认会对整个Store
的state
内容进行sessionStorage
储存。
strategies
是一个选项对象,用于配置持久化插件的行为。以下是一些常见的选项:
key
:自定义存储的 key,默认是defineStore
的第一个参数,即store.id
storage
:本地存储对象,默认为window.sessionStorage
paths
:state 中的字段名,按组打包储存以下是一个完整的示例:
import { ref, computed } from "vue";
import { defineStore } from "pinia";
export const useCounterStore = defineStore(
"counter",
() => {
const count = ref(1);
const total = ref(10);
const doubleCount = computed(() => count.value * 2);
function increment() {
count.value++;
}
function decrement() {
count.value--;
}
return { count, total, doubleCount, increment, decrement };
},
{
persist: {
enabled: true,
strategies: [
{
// 自定义存储的 key,默认是 defineStore 的第一个参数,即 store.id
key: "local",
// 可以指定任何 extends Storage 的实例,默认是 sessionStorage
storage: localStorage,
// state 中的字段名,按组打包储存
paths: ["count", "total"],
},
],
},
}
);
此时数据存储在了localStorage
中: