• vue3使用pinia实现数据缓存



    前言

    vue2以前一直使用vuex实现状态管理
    vue3之后推出了pinia…


    一、pinia是什么?

    直观、类型安全、轻便灵活的Vue Store,使用具有DevTools支持的组合api

    二、安装pinia

    由于pinia本身没有提供设置缓存的功能,不过可以结合pinia-plugin-persistedstate实现

    npm i pinia -S
    npm i pinia-plugin-persistedstate -S
    
    • 1
    • 2

    三、注册pinia

    • main.ts文件
    import { createApp } from "vue";
    import { createPinia } from "pinia";
    import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
    import App from "./App/index.vue";
    
    const app = createApp(App);
    // 注册  pinia , 并在 pinia 使用 piniaPluginPersistedstate
    app.use(createPinia().use(piniaPluginPersistedstate));
    app.mount("#app");
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    四、使用pinia

    大部分开发都默认在 stores 目录放置缓存相关文件

    定义数据及方法

    pinia有两种写法,其中一个是同vuex类似的选项式(这种才能结合pinia-plugin-persistedstate设置浏览器缓存),还有一个就是更符合vue3组合式写法

    • stores/mapState.ts (选项式)
    import { defineStore } from "pinia";
    
    export interface MapState {
      address: string;
    }
    const { SIS_STORE_NAME } = import.meta.env;
    
    export const useMapStore = defineStore(SIS_STORE_NAME + "map", {
      state: (): MapState => ({
        address: "",
      }),
      getters: {},
      actions: {
        setAdress(address: string) {
          this.address = address;
        },
        clearMessage() {
          this.address = "";
        },
      },
      persist: {
        /**
         * 使用的存储
         * @default $store.id
         */
        key: SIS_STORE_NAME + "map",
        /**
         * 存储位置
         * @default localStorage
         */
        storage: sessionStorage,
        /**
         * 需要设置缓存的state 如果未设置即存储所有state
         * @default undefined
         */
        // paths: [],
        /**
         * 存储之前
         * @default null
         */
        beforeRestore: () => {},
        /**
         * 存储之后
         * @default undefined
         */
        afterRestore: () => {},
        /**
         * 启用时在控制台中记录错误。
         * @default false
         */
        debug: true,
      },
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • stores/counter.ts (组合式)
    import { ref, computed } from "vue";
    import { defineStore } from "pinia";
    
    export const useCounterStore = defineStore("counter", () => {
      const count = ref(0);
      const doubleCount = computed(() => count.value * 2);
      function increment() {
        count.value++;
      }
    
      return { count, doubleCount, increment };
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    使用

    如果是字段数据,需要使用storeToRefs 获取为响应式的,方法不用
    虽然上述两种定义不同,但调用使用方式是一样的

    import { storeToRefs } from "pinia";
    import { useMapStore } from "./stores/mapState";
    import { useCounterStore } from "./stores/counter";
    
    const { address } = storeToRefs(useMapStore())
    const { setAdress, clearMessage } = useMapStore()
    setAdress('')
    clearMessage()
    
    const { count } = storeToRefs(useCounterStore())
    const { increment } = useCounterStore()
    increment()
    console.log(count)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    优化

    • stores/index.ts
    import type { App } from "vue";
    import { createPinia } from "pinia";
    import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
    
    const store = createPinia().use(piniaPluginPersistedstate);
    
    // 全局注册 store
    export function setupStore(app: App<Element>) {
      app.use(store);
    }
    export { store };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • main.ts
    import { createApp } from "vue";
    import App from "./App/index.vue";
    import { setupStore } from "./stores";
    const app = createApp(App);
    // 全局注册 状态管理(store)
    setupStore(app)
    app.mount("#app");
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    如有启发,可点赞收藏哟~

  • 相关阅读:
    python利用BUG让它免费啦~你在不知道就要后悔啦~
    Linux 下静态库与动态库的制作与使用
    【Python】python入门(一):JupyterLab安装、使用
    element-ui switch开关组件二次封装,添加loading效果,点击时调用接口后改变状态
    Aveva Marine VBNET 编程系列-搭建开发框架
    全栈开发学习记录:一个简单的node.js服务器以及用到的表、视图、存储过程和配套测试的前端.
    Python大数据之linux学习总结——day11_ZooKeeper
    XTU-OJ 1215-A+B V
    无涯教程-JavaScript - BIN2HEX函数
    mac 安装pandas教程并验证是否成功安装
  • 原文地址:https://blog.csdn.net/weiCong_Ling/article/details/134526596