getter方法的作用 vuex_vuex 中关于 mapGetters 的作用

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-29 15:36   11   0

mapGetters 工具函数会将 store 中的 getter 映射到局部计算属性中。它的功能和 mapState 非常类似,我们来直接看它的实现:

export function mapGetters (getters) {

const res = {}

normalizeMap(getters).forEach(({ key, val }) => {

res[key] = function mappedGetter () {

if (!(val in this.$store.getters)) {

console.error(`[vuex] unknown getter: ${val}`)

}

return this.$store.getters[val]

}

})

return res

}

mapGetters 的实现也和 mapState 很类似,不同的是它的 val 不能是函数,只能是一个字符串,而且会检查 val in this.$store.getters 的值,如果为 false 会输出一条错误日志。为了更直观地理解,我们来看一个简单的例子:

import { mapGetters } from 'vuex'

export default {

// ...

computed: {

// 使用对象扩展操作符把 getter 混入到 computed 中

...mapGetters([

'doneTodosCount',

'anotherGetter',

// ...

])

}

}

经过 mapGetters 函数调用后的结果,如下所示:

import { mapGetters } from 'vuex'

export default {

// ...

computed: {

doneTodosCount() {

return this.$store.getters['doneTodosCount']

},

anotherGetter() {

return this.$store.getters['anotherGetter']

}

}

}

再看一个参数 mapGetters 参数是对象的例子:

computed: mapGetters({

// 映射 this.doneCount 到 store.getters.doneTodosCount

doneCount: 'doneTodosCount'

})

经过 mapGetters 函数调用后的结果,如下所示:

computed: {

doneCount() {

return this.$store.getters['doneTodosCount']

}

}

.

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP