加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Vuex之理解Getters的用法实例

发布时间:2020-12-17 02:59:51 所属栏目:百科 来源:网络整理
导读:1.什么是getters 在介绍中我们了解到,在 Store 仓库里, state 就是用来存放数据,若是对数据进行处理输出,比如数据要过滤,一般我们可以写到 computed 中。但是如果很多组件都使用这个过滤后的数据,比如饼状图组件和曲线图组件,我们是否可以把这个数据

1.什么是getters

在介绍中我们了解到,在Store仓库里,state就是用来存放数据,若是对数据进行处理输出,比如数据要过滤,一般我们可以写到computed中。但是如果很多组件都使用这个过滤后的数据,比如饼状图组件和曲线图组件,我们是否可以把这个数据抽提出来共享?这就是getters存在的意义。我们可以认为,【getters】是store的计算属性。

2.如何使用

定义:我们可以在store中定义getters,第一个参数是state

state.style}

传参:定义的Getters会暴露为store.getters对象,也可以接受其他的getters作为第二个参数;

使用:

3.mapGetters

mapGetters辅助函数仅仅是将store中的getters映射到局部计算属性中,用法和mapState类似

4.源码分析

wrapGetters初始化getters,接受3个参数,store表示当前的Store实例,moduleGetters当前模块下所有的gettersmodulePath对应模块的路径

{ // 遍历先所有的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}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读