Pinia学习笔记之--核心概念Getters

本文详细介绍了 Pinia 中的 getters 的使用方法,包括如何定义、访问 getters,如何组合 getters,以及在不同场景下的用法。getters 类似于计算属性,可以缓存结果,提高性能,并允许组合使用。同时,文中还展示了在 Vue 组件中如何通过 setup() 或 Options API 访问 getters,以及在 TypeScript 中处理 getters 的类型问题。

Getters

getterStore状态的计算值完全相同。它们可以用defineStore()中的getters属性来定义。它们接收state作为第一个参数,以鼓励使用箭头函数:

export const  useStore = defineStore('main', {
    state: () => ({
        counter: 0
    }),
    getters: {
        doubleCount: (state) => state.counter * 2
    }
})

大多数时候,getter只依赖于状态,但是,它们可能需要使用其他getter。因此,当定义一个常规函数时,我们可以通过这个函数访问整个store实例,但需要定义返回的类型(在TypeScript中)。这是由于TypeScript中的一个已知限制,不会影响用箭头函数定义的getter,也不会影响不使用Thisgetter:

export const useStore = defineStore('mian', {
    state: (() => {
        counter: 0
    }),
    getters: {
        // 自动推断类型为nubmer
        doubleCount(state) {
            return state.counter * 2
        },
        // 返回的类型必须被设置
        doublePlusOne(): number {
            // autocompletion and typings for the whole store
            return this.doubleCount + 1
        }
    }
})

然后你可以直接访问store实例getter

<template>
    <p>Double count is {{ store.doubleCount }}</p>
</tempalte>
<script>
    export default {
        setup() {
            const store = useStore()
            return { store }
        }
    }
</script>

访问其它的getters

与计算属性一样,您可以组合多个getters。通过this访问任何其他的getters。即使您不使用TypeScript,您也可以使用JSDoc提示IDE输入的类型

export const useStore = defineStore('main', {
  state: () => ({
    counter: 0,
  }),
  getters: {
    // type is automatically inferred because we are not using `this`
    doubleCount: (state) => state.counter * 2,
    // here we need to add the type ourselves (using JSDoc in JS). We can also
    // use this to document the getter
    /**
     * Returns the counter value times two plus one.
     *
     * @returns {number}
     */
    doubleCountPlusOne() {
      // autocompletion ✨
      return this.doubleCount + 1
    },
  },
})

给getters传参数

Getter只是后台的计算属性,所以不可能向它们传递任何参数。但是,你可以从getter返回一个函数来接受任何参数:

export const useStore = defineStore('main', {
  getters: {
    getUserById: (state) => {
      return (userId) => state.users.find((user) => user.id === userId)
    },
  },
})

然后再组件中这样使用:

<script>
export default {
    setup() {
        const store = useStore()

        return {
            getUserById: store.getUserById
        }
    }
}
</script>
<template>
  <p>User 2: {{ getUserById(2) }}</p>
</template>

注意,当这样做时,getter不再被缓存,它们只是您调用的函数。然而,你可以在getter本身中缓存一些结果,这是不常见的,但更高效:

export const useStore = defineStore('main', {
  getters: {
    getActiveUserById(state) {
      const activeUsers = state.users.filter((user) => user.active)
      return (userId) => activeUsers.find((user) => user.id === userId)
    },
  },
})

访问其它实例的getters

要使用另一个store中的 getter,你可以直接在getter中使用它:

import { useOtherStore } from './other-store'

export const useStore = defineStore('main', {
  state: () => ({
    // ...
  }),
  getters: {
    otherGetter(state) {
      const otherStore = useOtherStore()
      return state.localData + otherStore.data
    },
  },
})

在setup()中的用法

你可以直接访问任何getter作为存储的属性(完全像state属性):

export default {
  setup() {
    const store = useStore()

    store.counter = 3
    store.doubleCount // 6
  },
}

Options API 中的用法

对于以下示例,您可以假设创建了以下store:

// Example File Path:
// ./src/stores/counterStore.js

import { defineStore } from 'pinia',

const useCounterStore = defineStore('counterStore', {
  state: () => ({
    counter: 0
  }),
  getters: {
    doubleCounter() {
      return this.counter * 2
    }
  }
})

使用 setup()

虽然Composition API并不适合所有人,但是setup()钩子可以让Pinia更容易在Options API中使用。不需要额外的帮助函数!

import { useCounterStore } from '../stores/counterStore'

export default {
  setup() {
    const counterStore = useCounterStore()

    return { counterStore }
  },
  computed: {
    quadrupleCounter() {
      return counterStore.doubleCounter * 2
    },
  },
}

不使用 setup()

你可以使用在前一节中使用的mapState()函数来映射到getter:

import { mapState } from 'pinia'
import { useCounterStore } from '../stores/counterStore'

export default {
  computed: {
    // gives access to this.doubleCounter inside the component
    // same as reading from store.doubleCounter
    ...mapState(useCounterStore, ['doubleCount'])
    // same as above but registers it as this.myOwnName
    ...mapState(useCounterStore, {
      myOwnName: 'doubleCounter',
      // you can also write a function that gets access to the store
      double: store => store.doubleCount,
    }),
  },
}
我希望借助本工作目录,参考Vue的文档一步一步学习Vue **参考文档** 可用的文档包括: -Vue 官方文档:(https://v2.cn.vuejs.org/) -Vue 社区提供的中文文档:https://v2.cn.vuejs.org/v2/guide/ **目录规划** 我目前创建了三个目录和一个文件 -@README.md:介绍本学习项目的使用方式 -./example:用于运行文档中提供的示例代码,根据要学习的示例的不同,后运行的示例代码可以覆盖之前的示例代码 -./notes:在跟着文档学习Vue过程中,记录Vue学习笔记 -./prompts:用于存放我和你交流所常用到的提示词 **笔记撰写** 对于在./notes中记录的学习笔记,请注意如下要求: -请使用Markdown格式撰写学习笔记 -一份笔记(即notes目录中的某个.md文件)不应该太长,原则不超过150行 **教学风格** 对于教学的方式,有如下要求: -你应该一边介绍我们所学的知识,一边撰写./notes的学习笔记 -你应当每次只输出尽可能少的内容,就像一个一对一的辅导老师,这样我可以通过简明扼要的引导来进行学习,而不是听长篇大论 现在,首先要做的三件事: 1.根据本项目的定位,撰写@README.md介绍本项目 2.根据我所期望的你在本项目中的身份定位,撰写@coding-teacher.mdc 3.深入阅读两份Vue文档,参考文档中知识的组织方式,编写教学大纲与@catalogue.md,我随后将进一步与你商讨和迭代这份教学大纲
04-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

绝对零度HCL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值