mapGetters 的作用__為什麼mapGetter前面有...(三個點是去掉{}的作用)
阿新 • • 發佈:2020-10-12
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