1.什么是
getters
vue
在介绍state中咱们了解到,在Store
仓库里,state
就是用来存放数据,如果对数据进行处理输出,好比数据要过滤,通常咱们能够写到computed
中。可是若是不少组件都使用这个过滤后的数据,好比饼状图组件和曲线图组件,咱们是否能够把这个数据抽提出来共享?这就是getters
存在的意义。咱们能够认为,【getters】是store的计算属性。vuex
2.如何使用segmentfault
定义:咱们能够在store
中定义getters
,第一个参数是stateapp
const getters = {style:state => state.style}
传参:定义的Getters
会暴露为store.getters
对象,也能够接受其余的getters
做为第二个参数;函数
使用:源码分析
computed: { doneTodosCount () { return this.$store.getters.doneTodosCount}
3.mapGettersthis
mapGetters
辅助函数仅仅是将store
中的getters
映射到局部计算属性中,用法和mapState
相似code
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
对应模块的路径get
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}