1.什么是getters
在介绍state中我们了解到,在Store
仓库里,state
就是用来存放数据,若是对数据进行处理输出,比如数据要过滤,一般我们可以写到computed
中。但是如果很多组件都使用这个过滤后的数据,比如饼状图组件和曲线图组件,我们是否可以把这个数据抽提出来共享?这就是getters
存在的意义。我们可以认为,【getters】是store的计算属性。
2.如何使用
定义:我们可以在store
中定义getters
,第一个参数是state
const getters = {style:state => state.style}
传参:定义的Getters
会暴露为store.getters
对象,也可以接受其他的getters
作为第二个参数;
使用:
computed: { doneTodosCount () { return this.$store.getters.doneTodosCount}
3.mapGetters
mapGetters
辅助函数仅仅是将store
中的getters
映射到局部计算属性中,用法和mapState
类似
import { mapGetters } from 'vuex' computed: { // 使用对象展开运算符将 getters 混入 computed 对象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter',])} //给getter属性换名字 mapGetters({ // 映射 this.doneCount 为 store.getters.doneTodosCount doneCount: 'doneTodosCount' })
4.源码分析
wrapGetters
初始化getters
,接受3个参数,store
表示当前的Store
实例,moduleGetters
当前模块下所有的getters
,modulePath
对应模块的路径
function `wrapGetters` (store, moduleGetters, modulePath) { Object.keys(moduleGetters).forEach(getterKey => { // 遍历先所有的getters const rawGetter = moduleGetters[getterKey] if (store._wrappedGetters[getterKey]) { console.error(`[vuex] duplicate getter key: ${getterKey}`) // getter的key不允许重复,否则会报错 return } store._wrappedGetters[getterKey] = function `wrappedGetter` (store{ // 将每一个getter包装成一个方法,并且添加到store._wrappedGetters对象中, return rawGetter( //执行getter的回调函数,传入三个参数,(local state,store getters,rootState) getNestedState(store.state, modulePath), // local state //根据path查找state上嵌套的state store.getters, // store上所有的getters store.state // root state)}}) } //根据path查找state上嵌套的state function `getNestedState` (state, path) { return path.length ? path.reduce((state, key) => state[key], state): state}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
暂无“Vuex之理解Getters的用法实例”评论...
更新动态
2024年09月27日
2024年09月27日
- 张学友.1999-有个人【宝丽金】【WAV+CUE】
- 纯音入心系列纯音乐《古筝佛曲》1CD[MP3][411.1MB]
- 纯音入心系列纯音乐《古筝世界名曲》1CD[MP3][38.9MB]
- 纯音入心系列纯音乐《古筝新奏-菩提妙音》1CD[MP3][112.3MB]
- 陈思安.1993-怀念福建金曲5CD【歌丽美】【WAV+CUE】
- 张学友.1999-有个人【宝丽金】【WAV+CUE】
- 许美静.1999-快乐无罪【上华】【WAV+CUE】
- 群星.2024-Jambo.Medley(BEYOND40周年·致敬2)【Kinns】【FLAC分轨】
- 林翠萍.1991-舞曲世界2辑【星河】【WAV+CUE】
- 关智斌.2007-In.Progress【英皇娱乐】【FLAC分轨】
- 群星.2000-电影主题曲原声带·琼瑶的世界【歌林】【WAV+CUE】
- 范世錡.2024-錡妙夜(EP)【天娱传媒】【FLAC分轨】
- 谭咏麟.2000-魅力千禧演唱会2CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 纯音入心系列纯音乐《器乐古筝》1CD[MP3][239MB]
- 纯音入心系列纯音乐《华夏民乐之古筝篇》1CD[MP3][192MB]