手机版

谈谈Vuex的getters属性的具体用法

时间:2021-08-26 来源:互联网 编辑:宝哥软件园 浏览:

什么是吸气剂

在状态的介绍中,我们知道在Store仓库中,状态用于存储数据。如果数据被处理和输出,比如过滤数据,我们一般可以用computed来写。但是如果很多组件使用这种过滤后的数据,比如饼图组件和图形组件,我们能不能提取这些数据并共享呢?这就是吸气剂存在的原因。我们可以认为[getter]是商店的一个计算属性。

源代码分析

WrapGetters初始化getter并接受三个参数,store表示当前的Store实例,moduleGetters的当前模块下的所有getter,modulePath对应于模块的路径

函数“wrapGetters ”(存储,模块模式,模块路径){object。钥匙(模块吸气剂)。foreach(getter key={//traverse all getter const raw getter=module getter[getter key]If(store。_ wrapped getter[getter key]){ console。错误(`[vuex]重复的getter键: $ { getter key } `)//getter的键不能重复。否则,将报告一个错误:return} store。_ wrapppedgetters[getter key]=function ` wrapped getter `(store {//将每个getter包装到一个方法中,并将其添加到存储中。_包装的getters对象。Return rawGetter(//执行Getter的回调函数,并传入三个参数(本地状态、存储getter、根状态)getnestedstate(存储。状态、模块路径)。//local state //根据路径在state上查找嵌套statestore.getters,//all getter store . state//root state)} })}//查找嵌套state function ` getnested state `(state,path) {return path.length?路径。reduce ((state,key)=state [key],state) : state} 1应用场景

假设我们在Vuex中定义了一个数组:

Const store=newvuex。商店({state: {list: [1,3,5,7,9,20,30]}.})业务场景想要过滤掉大于5的数字。立即想到的方法可能是:过滤组件的计算属性:

template div { { list } }/div/template script导出默认值{ name: 'index.vue ',computed: { list() {返回此。$ store . state . list . filter(item=item 5);} } }/脚本效果:

虽然实现了该功能,但如果其他组件也需要过滤数据,则必须复制出index.vue中的计算过滤代码。如果过滤规则发生变化,这些组件中的计算属性就要一个一个修改,很难维护。在这个场景中,我们可以使用getters属性O(_)O~

2基本用法

main.js:

const store=new Vuex。Store({ state: { list: [1,3,5,7,9,20,30] },getter s : { filtered list : state={ return state . list . filter(item=item 5)} })index . vue:

脚本导出默认{ name: 'index.vue ',computed : { list(){ return this。$ store . getter s . filtered list;} } }/脚本效果达到,过滤规则只需要维护在一个地方。

3内部依赖

吸气剂可以依赖于其他定义的吸气剂。例如,如果我们需要计算过滤列表的数量,我们可以依靠以前定义的过滤函数。

main.js:

const store=new Vuex。Store({ state: { list: [1,3,5,7,9,20,30] },getter s : { filtered list : state={ return state . list . filter(item=item 5)},listCount: (state,getter)={ return getter . filtered list . length;} }})index.vue:

模板div筛选列表:{{list}} br列表长度:{ { list count } }/div/模板脚本导出默认值{name:' index.vue ',computed : { list(){ return this。$ store . getter s . filtered list;},listCount() {返回这个。$ store . getter s . listcount;} } }/脚本效果:

以上就是本文的全部内容。希望对大家的学习有帮助,支持我们。

版权声明:谈谈Vuex的getters属性的具体用法是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。