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'] } }
注:在vuex.common.js中定義了mapGetter