前言
pinia和 vuex 存在同一个问题:页面刷新,store中的状态无法保持
同样也可以用插件解决: pinia-plugin-persistedstate
一、安装
yarn:
yarn add pinia-plugin-persistedstate
npm:
npm install pinia-plugin-persistedstate
二、引入
main.js
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
三、配置 store
1、 可以在各个store中分别配置
以下两种store的配置方式不同:
选项式语法的store
(persist 配在 defineStore 的第二个参数里)
// 通过 options 创建
import { defineStore } from "pinia";
export const useStoreA = defineStore("storeA", {
state: () => ({
count: 0,
}),
// 持久化配置:若仅配置 true,则全部存储
// persist: true,
persist: {
// 存储的 key, 默认是 defineStore 的第一个参数
key: "A",
// 存储位置,默认 localStorage
storage: localStorage,
// 指定内容
paths: ["count"],
},
});
组合函数式的store
(persist 配在 defineStore 的第三个参数里)
// 通过组合式函数创建
import { defineStore } from "pinia";
import { ref } from "vue";
export const useStoreB = defineStore(
"storeB",
() => {
const count = ref(0);
return { count };
},
{
// 若仅配置 true,则全部存储
// persist: true,
persist: {
// 存储的 key, 默认是 defineStore 的第一个参数
key: "B",
// 存储位置,默认 localStorage
storage: localStorage,
// 指定内容
paths: ["count"],
},
}
);
2、也可以在 main.js 中做一些统一配置
// 统一配置
import { createPersistedState } from "pinia-plugin-persistedstate";
pinia.use(
createPersistedState({
// 存储的 key
key: (id) => `__persisted__${id}`,
})
);