目录:
persist.ts 可存储到本地
import { PersistedStateOptions } from "pinia-plugin-persistedstate";
/**
* @description pinia 持久化参数配置
* @param {String} key 存储到持久化的 name
* @param {Array} paths 需要持久化的 state name
* @return persist
* */
const piniaPersistConfig = (key: string, paths?: string[]) => {
const persist: PersistedStateOptions = {
key,
storage: localStorage,
// storage: sessionStorage,
paths
};
return persist;
};
export default piniaPersistConfig;
index.ts
import { createPinia } from "pinia";
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";
// pinia persist
const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
export default pinia;
main.ts导入
import pinia from "@/stores";
createApp(App).use(pinia)
使用:
存储数据:general.ts
import { defineStore } from "pinia";
import piniaPersistConfig from "@/stores/helper/persist";
interface GeneralType {
linesName: string;
}
export const useGeneralStore = defineStore({
id: "live-General",
state: (): GeneralType => ({
linesName: "全部"
}),
getters: {},
actions: {
// Set setGeneral
setGeneral(linesName: string) {
this.linesName = linesName;
}
},
persist: piniaPersistConfig("live-linesName") // 持久化操作
});
修改数据:
import { useGeneralStore } from "@/stores/modules/general";
const generalStore = useGeneralStore();
generalStore.setGeneral(linesName.value);
直接使用:generalStore.linesName
监听piain中的数据更新:数据变化就会触发
generalStore.$subscribe((linesNames, state) => {
console.log(linesNames, state);
});