• 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

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

  • 相关阅读:
    SpringMVC拦截器、异常、其他注解
    Stream.toList()和Collectors.toList()的性能比较
    冒泡排序知识点
    MySQL-----事务管理
    .NET 使用自带 DI 批量注入服务(Service)和 后台服务(BackgroundService)
    照片怎么压缩变小?
    c语言 数据结构 二叉树
    聚焦千兆光模块和万兆光模块的测试技术及设备
    nuxtjs生命周期、项目创建、声明式导航与编程式导航、动态路由、嵌套路由、配置式路由、定制默认应用模板、扩展默认布局
    系统异常SVC与PendSV指令
  • 原文地址:https://blog.csdn.net/weiCong_Ling/article/details/134526596