vuex 中關於 mapGetters 的作用


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

.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM