• vue3 - pinia 中的 storeToRefs


    interface.d.ts文件

    export interface useMyStore {
      id: string
      content: string
      type: string
      status: boolean
      collected: boolean
      date: string
      quality: string
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    useMyStore.js文件

    const msgData = [
      {
        id: '123',
        content: '腾讯大厦一楼改造施工项目 已通过审核!',
        type: '合同动态',
        status: true,
        collected: false,
        date: '2021-01-01 08:00',
        quality: 'high',
      },
      {
        id: '124',
        content: '三季度生产原材料采购项目 开票成功!',
        type: '票务动态',
        status: true,
        collected: false,
        date: '2021-01-01 08:00',
        quality: 'low',
      },
    ]
    
    type MsgDataType = typeof msgData;
    
    export const useMyStore = defineStore('useMyStore', {
      state: () => ({
        msgData,
      }),
    
      getters: {
        unreadMsg: (state) => state.msgData.filter((item: useMyStore) => item.status),
        readMsg: (state) => state.msgData.filter((item: useMyStore) => !item.status),
      },
    
      actions: {
        setMsgData(data: MsgDataType) {
          this.msgData = data
        },
      },
    
      persist: 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

    index.vue文件

    import { storeToRefs } from 'pinia'
    import { useMyStore } from '@/store'
    
    const myStore = useMyStore()
    const { msgData, unreadMsg, readMsg } = storeToRefs(myStore)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    storeToRefs 是 Pinia 库中的一个辅助函数,用于将存储对象(store)中的属性转换为响应式的引用。

    在上面的例子中,

    使用 storeToRefs 函数将存储对象 myStore 中的 msgDataunreadMsgreadMsg 属性转换为响应式的引用,

    这意味着当存储对象中的这些属性发生变化时,引用也会相应地更新。

    这样做的好处是,

    我们可以在组件中直接使用 msgDataunreadMsgreadMsg 这些响应式引用,而不需要手动调用 ref 函数创建响应式引用,

    这样可以简化代码,并确保在模板中使用这些属性时能够保持响应式。

    总之,storeToRefs 函数是用于将存储对象中的属性转换为响应式引用的便捷方法,有助于简化在 Vue 3 中使用 Pinia 进行状态管理的过程。

  • 相关阅读:
    什么是PCB中的光学定位点,不加可不可以?
    DAO 中存在的不足和优化方案
    黑豹程序员-架构师学习路线图-百科:Java
    通讯录的实现(文件版本)
    Linux操作系统——线程概念
    数据开发流程图
    R语言时间序列数据算术运算:使用log函数将时间序列数据的数值对数化、使用diff函数计算对数化后的时间序列数据的逐次差分(计算价格的对数差分)
    StarRocks 的学习笔记
    LeetCode每日一题(2256. Minimum Average Difference)
    面试中的问题
  • 原文地址:https://blog.csdn.net/pig_ning/article/details/134442913