首页 > 其他 > 详细

Vue如何使用mapGetters

时间:2020-03-11 10:26:12      阅读:65      评论:0      收藏:0      [点我收藏+]

转载:https://www.cnblogs.com/crazycode2/p/7636082.html

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‘]
    }
}

 

Vue如何使用mapGetters

原文:https://www.cnblogs.com/flypig666/p/12460433.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!