首页 > 其他分享 >vue3-pinia保持数据时效性,不会因为刷新浏览器丢失实时数据(pinia-plugin-persistedstate/$subscribe)

vue3-pinia保持数据时效性,不会因为刷新浏览器丢失实时数据(pinia-plugin-persistedstate/$subscribe)

时间:2024-08-30 09:53:27浏览次数:9  
标签:const title plugin subscribe pinia persistedstate import store

1.方法一(pinia-plugin-persistedstate)

1.安装插件-pinia-plugin-persistedstate

yarn add pinia-plugin-persistedstate
npm i pinia-plugin-persistedstate

2.在 pinia 中注册

import { createPinia } from 'pinia';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';

const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);

export default pinia;

3.自定义持久化参数配置

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;

4.如何使用(setup 写法)

import { defineStore } from 'pinia';
import { ref } from 'vue';
import piniaPersistConfig from '@/store/helper/persist';

const storeDemo = defineStore(
  'store-demo',
  () => {
    const title = ref('demo');

    const setTitle = () => {
      title.value = '我是 store 改变的值';
    };

    return {
      title,
      setTitle,
    };
  },
  {
    persist: piniaPersistConfig('gloabl-demo'),
  }
);

export default storeDemo;

5.如何使用(options 写法)

import { defineStore } from 'pinia';
import { GlobalState } from '../type';
import { DEFAULT_PRIMARY } from '@/config/layout.config';
import piniaPersistConfig from '@/store/helper/persist';

export const useGlobalStore = defineStore({
  id: 'skam-global',
  state: (): GlobalState => ({
	layout: 'classic',
	// element 组件大小
	assemblySize: 'default',
	// 当前系统语言
	language: null,
	// 当前页面是否全屏
	maximize: false,
	// 主题
	theme: 'dark',
	// 主题颜色
	primary: DEFAULT_PRIMARY,
	// 深色模式
	isDark: false,
	// 灰色模式
	isGrey: false,
	// 色弱模式
	isWeak: false,
	// 侧边栏反转
	asideInverted: false,
	// 头部反转
	headerInverted: false,
	// 折叠菜单
	isCollapse: false,
	// 菜单手风琴
	accordion: true,
	// 面包屑导航
	breadcrumb: true,
	// 面包屑导航图标
	breadcrumbIcon: true,
	// 标签页
	tabs: true,
	// 标签页图标
	tabsIcon: true,
	// 页脚
	footer: true,
	// 布局模式
	mode: 'inline',
  }),
  getters: {},
  actions: {
	// 设置全局属性
	setGlobalState(...args: any) {
	  this.$patch({ [args[0]]: args[1] });
	},
  },
  persist: piniaPersistConfig('geeker-global'),
});

export default useGlobalStore;

6.总结:每当通过 ref 创建的 title 值改变时,locastorage 就会更新值。

2.方法二

1.pinia 配置

import { createPinia } from 'pinia';

const pinia = createPinia();

export default pinia;

2.globalDemo

import { defineStore } from 'pinia';
import { ref } from 'vue';

const storeDemo = defineStore('store-demo', () => {
  const title = ref('demo');

  const setTitle = () => {
	title.value = '我是 store 改变的值';
  };

  return {
	title,
	setTitle,
  };
});

export default storeDemo;

3.页面使用(setup)

<template>
  <div>{{ title }}</div>
  <a-button @click="pageHandle">页面改变 title</a-button>
  <a-button @click="() => useGlobalDemo.setTitle()">store改变 title</a-button>
</template>
import { useStore } from '@/store';
import { storeToRefs } from 'pinia';
// store
const { useGlobalDemo } = useStore();
const { title } = storeToRefs(useGlobalDemo); // storeToRefs作用是让解构出来的 title 变成响应式

onMounted(() => {
  useGlobalDemo.title = '修改 title 的值';
});

const pageHandle = () => {
  useGlobalDemo.title = '页面更改';
};

const demoF = (mutation, state) => {
  localStorage.setItem('subscribe-demo', JSON.stringify(state));
};
useGlobalDemo.$subscribe(demoF, { detached: true }); // $subscribe方法,detached参数作用是当组件被卸载时,依旧保留它们(demoF函数,如果detached:false 或者不传,组件卸载时,demoF函数不生效)

标签:const,title,plugin,subscribe,pinia,persistedstate,import,store
From: https://www.cnblogs.com/songkomei/p/18388075

相关文章