Pinia 数据持久化储存(pinia-plugin-persistedstate),简单入门使用(有手就行系列)

1.安装依赖npm install  pinia-plugin-persistedstate

2.在main.js导入

import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';
app.use(createPinia().use(piniaPluginPersistedstate))

完整代码参考

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';
import App from './App.vue'
import router from './router'
import vant from 'vant';
import 'vant/lib/index.css';

import './assets/main.css'

// 请求接口封装
import http from './http/http'
window.$http = http

// 组件与组件之间通信
import mitt from "mitt"
window.$mybus = mitt()

import Vconsole from 'vconsole';

const vConsole = new Vconsole();


const app = createApp(App)

app.use(createPinia())
app.use(createPinia().use(piniaPluginPersistedstate))

app.use(router)
app.use(vant)
app.use(vConsole);

// 定义全局Loading组件
import MyLoading from './components/MyLoading.vue';
app.component('MyLoading', MyLoading)
//定义全局Svg组件
import SvgIcon from '@/components/SvgIcon.vue';
app.component('SvgIcon', SvgIcon)

app.mount('#app')
const onFail = () => {
    console.log("失败",);
}
const onSuccess = () => {
    console.log("成功",);
}
document.addEventListener("deviceready", () => {
    AppUpdate.checkAppUpdate(onSuccess, onFail, import.meta.env.VITE_APP_UPD_URL);
    StatusBar.overlaysWebView(true);
    // cordova.plugins.backgroundMode.enable();//软件保活
}, false);

3.开启存储

  persist: {

    enabled: true,

  },

参考代码

import { defineStore } from 'pinia';
export const useSelectAnnotationLayerStore = defineStore('selectAnnotationLayerelectAnnotationLayerStore', {
  state: () => ({
    selectAnnotationLayer: {
      pointLayer: '物探测点',
      lineLayer: '物探测线',
      polygonLayer: '不良地质体',
    },
    selectVectorLayerCheckedList: ['物探测点', '调绘点', '点采集', '物探测线', '界线', '不良地质体'], //选中的矢量图层
    selectGeologicalLayerCheckedList: [], //选中的区域地质图层
    allGeologicalLayerList: [{ label: '广东构造体系图', value: 'L4674fbe9a3c24eba8f6b2bc4ca88349d' }],
  }),
  getters: {},
  actions: {
    SET_SELECT_ANNOTATION_LAYER(data) {
      this.selectAnnotationLayer = data;
    },
    SET_SELECT_VECTORLAYER_CHECKED(data) {
      this.selectVectorLayerCheckedList = data;
    },
    SET_SELECT_GEOLOGICAL_LAYER_CHECKED(data) {
      this.selectGeologicalLayerCheckedList = data;
    },
    SET_ALL_GEOLOGICAL_LAYER_CHECKED(data) {
      this.allGeologicalLayerList = data;
    },
  },
  persist: {
    enabled: true,
  },
});

4.查看SessionStorage是否缓存成功

Pinia 数据持久化储存(pinia-plugin-persistedstate),简单入门使用(有手就行系列)_第1张图片

5.补充

默认将数据存放在浏览器的localstore。

将store的state中的数据进行部分缓存(使用paths)

  persist: {
    enabled: true,
    paths: ['selectGeologicalLayerCheckedList', 'allGeologicalLayerList'],
  },

Pinia 数据持久化储存(pinia-plugin-persistedstate),简单入门使用(有手就行系列)_第2张图片

按图上搜到的方法并不可以,可能api过时了,需要的可以参考官方文档

Configuration | pinia-plugin-persistedstate

你可能感兴趣的:(javascript,开发语言,ecmascript)