如何在Vuex中使用getter属性

  介绍

本篇文章为大家展示了如何在Vuex中使用getter属性,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

wrapGetters初始化getter,接受3个参数,存储表示当前的商店实例,moduleGetters当前模块下所有的getter, modulePath对应模块的路径

,, function “wrapGetters”, (moduleGetters,商店,还以为;modulePath), {   ,才能种(moduleGetters) .forEach (getterKey =祝辞,{   ,,,,,//,遍历先所有的getter   ,,,const  rawGetter =, moduleGetters [getterKey]   ,,,if  (store._wrappedGetters [getterKey]), {   ,,,,console.error (“[vuex], duplicate  getter 关键:,$ {getterKey} ')   ,,,,,//,getter的关键不允许重复,否则会报的错   ,,,,回来   ,,,}   ,,,store._wrappedGetters [getterKey],=, function “wrappedGetter”,(存储{   ,,,,,//,将每一个getter包装成一个方法,并且添加到store._wrappedGetters对象中,   ,,,,,return  rawGetter (   ,,,,,,//执行getter的回调函数,传入三个参数,(local 状态,store  getter rootState)   ,,,,,getNestedState (modulePath store.state也),,//,local 状态   ,,,,,,//根据路径查找状态上嵌套的state    ,,,,,store.getters,,   ,,,,,,,//,商店上所有的getter   ,,,,,store.state    ,,,,,,,,//,root 状态)}}),   ,,}   ,,   ,,//根据路径查找状态上嵌套的state    function 才能“getNestedState”,(状态,,路径),{   ,,,,return  path.length   ,,,,,?,path.reduce((,,键),=祝辞,状态(关键),状态):,状态}

<强> 1应用场景

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

const  store =, new  Vuex.Store ({   ,,状态:{   ,,,列表:(1、3、5、7、9,20岁,30)   ,,}   ,……   })

业务场景希望过滤出大于5的数。马上想到的方法可能的是:在组件的计算属性中进行过滤:

& lt; template>   & lt;才能div>   ,,,{{列表}}   & lt;才能/div>   & lt;/template>   & lt; script>   export 才能;default  {   ,,,的名字:,“index.vue",   ,,,:计算,{   ,,,,,()列表,{   ,,,,,,,return 美元。store.state.list.filter (item =祝辞,item 祝辞,5);   ,,,,,}   ,,,}   ,}   & lt;/script>

效果:

如何在Vuex中使用getter属性

功能虽然实现了,但如果其它组件也需要过滤后的数据,那么就得把索引。vue中的计算过滤代码复制出来。如果过滤规则发生变化,还得一一修改这些组件中的计算属性,很难维护。这种场景下,我们就可以使用getter属性啦O (∩_∩) O ~

<强> 2基础用法

主要。js:

const  store =, new  Vuex.Store ({   ,,状态:{   ,,,列表:,(1,3,5,7,9日,20日,30)   ,,},   getter才能:{   ,,,filteredList:, state =祝辞,{   ,,,,,return  state.list.filter (item =祝辞,item 祝辞,5)   ,,,}   ,,}   })

索引。vue:

& lt; script>   export 才能;default  {   ,,,的名字:,“index.vue",   ,,,:计算,{   ,,,,,()列表,{   ,,,,,,,return 这个。store.getters.filteredList美元;   ,,,,,}   ,,,}   ,,}   & lt;/script>

效果达到了,而且只需要在一处维护过滤规则即可。

<强> 3内部依赖

getter可以依赖其它已经定义好的getter。比如我们需要统计过滤后的列表数量,就可以依赖之前定义好的过滤函数。

主要。js:

const  store =, new  Vuex.Store ({   ,,状态:{   ,,,列表:,(1,3,5,7,9日,20日,30)   ,,},   getter才能:{   ,,,filteredList:, state =祝辞,{   ,,,,,return  state.list.filter (item =祝辞,item 祝辞,5)   ,,,},   ,,,listCount:,(状态,,getter),=祝辞,{   ,,,,,return  getters.filteredList.length;   ,,,}   ,,}   })

索引。vue:

& lt; template>      & lt;才能div>   ,,,过滤后的列表:{{列表}}   ,,,& lt; br>   ,,,列表长度:{{listCount}}   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

如何在Vuex中使用getter属性