pinia 的使用(四)—— getters
文章目录1、Getters① getter声明与使用② 将参数传递给 getters (回调函数)③ getter中的this④ 访问其它getters⑤ 访问其它容器的actions 或getter1、Getters① getter声明与使用Getter 完全等同于 Store 状态的计算属性;Getters 函数的第一个参数是 state 对象;在src/store/index.ts文件中去写
·
文章目录
1、Getters
① getter 声明与使用
-
Getter 完全等同于 Store 状态的计算属性;Getters 函数的第一个参数是
state
对象; -
在
src/store/index.ts
文件中去写一个getters,来体验一下:import { defineStore } from 'pinia' // 导入 pinia 中的功能模块 // 创建容器 // 参数一:容器名 // 参数二:容器的内容 const useMainStore = defineStore('main', { // pinia 状态管理的数据,通过箭头函数返回一个对象 // 相当于 vue 中的 data 数据 state: () => { return { message1: 'Hello', message2: 'Pinia', count: 1, number: 666 } }, // 相当于 vue 中的 computed 计算属性 getters: { // 定义的 getters,第一个参数就是该容器的 state comp(state) { return ++state.count } }, // 相当于 vue 中的 methods 方法 actions: { // 1、count 加法方法 addCount() { this.count++ } } }) // 导出容器 export { useMainStore }
-
在页面组件中可以直接去调用该容器的getters方法:
<template> <!-- 后面相同的调用,都是基于第一次计算的值 --> <p>{{ mainStore.comp }}</p> <p>{{ mainStore.comp }}</p> <p>{{ mainStore.comp }}</p> </template> <script setup lang="ts"> // 导入 pinia 实例 import { useMainStore } from '../store/index' // 实例化容器 const mainStore = useMainStore() </script> <style scoped></style>
-
可以查看页面效果,只会调用该getters一次,和计算属性一样,都存在缓存:
② 将参数传递给 getters (回调函数)
-
Getter 只是幕后的计算属性,因此无法向它们传递任何参数。但是,您可以从 getter 返回一个函数来接受任何参数,请注意,执行此操作时,getter 不再缓存,它们只是您调用的函数。但是,您可以在 getter 本身内部缓存一些结果,这并不常见,但性能更高:
import { defineStore } from 'pinia' // 导入 pinia 中的功能模块 // 创建容器 // 参数一:容器名 // 参数二:容器的内容 const useMainStore = defineStore('main', { // pinia 状态管理的数据,通过箭头函数返回一个对象 // 相当于 vue 中的 data 数据 state: () => { return { message1: 'Hello', message2: 'Pinia', count: 1, number: 666 } }, // 相当于 vue 中的 computed 计算属性 getters: { // 定义的 getters,第一个参数就是该容器的 state comp(state) { return (num: number) => { return state.count + num } } }, // 相当于 vue 中的 methods 方法 actions: { // 1、count 加法方法 addCount() { this.count++ } } }) // 导出容器 export { useMainStore }
-
然后在组件中使用它们:
<template> <!-- 后面相同的调用,都是基于第一次计算的值 --> <p>{{ mainStore.comp(2) }}</p> <p>{{ mainStore.comp(3) }}</p> <p>{{ mainStore.comp(4) }}</p> </template> <script setup lang="ts"> // 导入 pinia 实例 import { useMainStore } from '../store/index' // 实例化容器 const mainStore = useMainStore() </script> <style scoped></style>
-
可以查看页面的效果:
注意: 如果给getters传参,返回的函数不会被缓存
③ getter中的this
-
getter中同样可以使用 this,但是 TS 无法推导类型,需要手动指定返回值类型:
// 类似于组件的computed,用来封装计算属性,有缓存的功能 getters: { // 传入 state [可选参数] // computeds(state){ // console.log('getter运行了') // return state.count + 1 // } // !getter 中同样可以使用 this ,但是 TS 无法推导类型,需要手动指定返回值类型 computeds():number { console.log('getter运行了') return this.count + 1 } },
④ 访问其它getters
-
与计算属性一样,您可以组合多个 getter。通过此访问任何其他 getter:
getters: { computeds():number{ console.log('getter运行了') return this.count+2 }, double():number{ this.foo = this.computeds * 2 return this.foo } },
⑤ 访问其它容器的actions 或getter
- 直接导入并实例化容器后,使用即可,与前面的跨容器调用一致,不再展示示例代码
更多推荐
所有评论(0)