mapState
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// 箭頭函數(shù)可以讓代碼非常簡潔
count: state => state.count,
// 傳入字符串 'count' 等同于 `state => state.count`
countAlias: 'count',
// 想訪問局部狀態(tài),就必須借助于一個(gè)普通函數(shù)五鲫,函數(shù)中使用 `this` 獲取局部狀態(tài)
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
經(jīng)過 mapState 函數(shù)調(diào)用后的結(jié)果嗦锐,如下所示:
import { mapState } from 'vuex'
export default {
// ...
computed: {
count() {
return this.$store.state.count
},
countAlias() {
return this.$store.state['count']
},
countPlusLocalState() {
return this.$store.state.count + this.localCount
}
}
}
mapGetters
mapGetters 的實(shí)現(xiàn)也和 mapState 很類似,不同的是它的 val 不能是函數(shù)筹燕,只能是一個(gè)字符串鹊奖,而且會(huì)檢查 val in this.$store.getters 的值偎痛,如果為 false 會(huì)輸出一條錯(cuò)誤日志。
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用對象擴(kuò)展操作符把 getter 混入到 computed 中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
經(jīng)過 mapGetters 函數(shù)調(diào)用后的結(jié)果偷俭,如下所示:
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
doneTodosCount() {
return this.$store.getters['doneTodosCount']
},
anotherGetter() {
return this.$store.getters['anotherGetter']
}
}
}
mapMutations
函數(shù)的實(shí)現(xiàn)幾乎也和 mapActions 一樣,唯一差別就是映射的是 store 的 commit 方法佛猛。為了更直觀地理解惑芭,我們來看一個(gè)簡單的例子
import { mapMutations } from 'vuex'
export default {
// ...
methods: {
...mapMutations([
'increment' // 映射 this.increment() 到 this.$store.commit('increment')
]),
...mapMutations({
add: 'increment' // 映射 this.add() 到 this.$store.commit('increment')
})
}
}
經(jīng)過 mapMutations 函數(shù)調(diào)用后的結(jié)果,如下所示:
import { mapActions } from 'vuex'
export default {
// ...
methods: {
increment(...args) {
return this.$store.commit.apply(this.$store, ['increment'].concat(args))
}
add(...args) {
return this.$store.commit.apply(this.$store, ['increment'].concat(args))
}
}
}