#### mapState
通過前面的學習,我們知道,從 store 實例中讀取狀態最簡單的方法就是在[計算屬性](https://cn.vuejs.org/guide/computed.html)中返回某個狀態。
那么,當一個組件需要獲取多個狀態的時候,怎么辦?是不是這樣:
~~~kotlin
export default {
...
computed: {
a () {
return store.state.a
},
b () {
return store.state.b
},
c () {
return store.state.c
},
...
}
}
~~~
當然,這樣是沒問題的,但是總感覺寫起來很難受,看起來更難受是吧!既然這么容易我們就感受到了,Vuex 能感受不到嗎,能忍得了嗎?
絕對不能忍,所以 `mapState` 輔助函數被創造了出來,用來搞定這個人人為之咬牙切齒的痛點。
~~~jsx
// 在單獨構建的版本中輔助函數為 Vuex.mapState
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// 箭頭函數可使代碼更簡練
a: state => state.a,
b: state => state.b,
c: state => state.c,
// 傳字符串參數 'b'
// 等同于 `state => state.b`
bAlias: 'b',
// 為了能夠使用 `this` 獲取局部狀態
// 必須使用常規函數
cInfo (state) {
return state.c + this.info
}
})
}
~~~
通過上面的示例,可以了解到,我們可以直接把需要用到的狀態全部存放在 `mapState` 里面進行統一管理,而且還可以取別名,做額外的操作等等。
如果所映射的計算屬性名稱與 state 的子節點名稱相同時,我們還可以更加簡化,給 `mapState` 傳一個字符串數組:
~~~cpp
computed: mapState([
// 映射 this.a 為 store.state.a
'a',
'b',
'c'
])
~~~
因為 `computed` 這個計算屬性接收的是一個對象,所以由上面的示例代碼可以看出,`mapState` 函數返回的是一個對象,現在如果想要和局部的計算屬性混合使用的話,可以使用 ES6 的語法這樣寫來大大簡化:
~~~cpp
computed: {
localComputed () {
...
},
// 使用對象展開運算符將此對象混入到外部對象中
...mapState({
// ...
})
}
~~~
了解了 `mapState` 輔助函數后,接下來的幾個輔助函數的用法也基本上都差不多了,我們繼續往下看。
#### mapGetters
這個和 `mapState` 基本上沒啥區別,簡單看下官方的例子,就懂了:
~~~jsx
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
~~~
取個別名,那就用對象的形式,以下示例的意思就是把 `this.doneCount` 映射為 `this.$store.getters.doneTodosCount`。
~~~css
mapGetters({
doneCount: 'doneTodosCount'
})
~~~
#### mapMutations
直接看示例代碼:
~~~jsx
import { mapMutations } from 'vuex'
export default {
// ...
methods: {
...mapMutations([
// 將 `this.increment()` 映射為
// `this.$store.commit('increment')`
'increment',
// `mapMutations` 也支持載荷:
// 將 `this.incrementBy(amount)` 映射為
// `this.$store.commit('incrementBy', amount)`
'incrementBy'
]),
...mapMutations({
// 將 `this.add()` 映射為
// `this.$store.commit('increment')`
add: 'increment'
})
}
}
~~~
簡直不要太好用,連載荷也可以直接支持。
#### mapActions
和 `mapMutations` 用法一模一樣,換個名字即可。
~~~jsx
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
// 將 `this.increment()` 映射為
// `this.$store. dispatch('increment')`
'increment',
// `mapActions` 也支持載荷:
// 將 `this.incrementBy(amount)` 映射為
// `this.$store. dispatch('incrementBy', amount)`
'incrementBy'
]),
...mapActions({
// 將 `this.add()` 映射為
// `this.$store. dispatch('increment')`
add: 'increment'
})
}
}
~~~
想要在組件中調用,直接 `this.xxx` 就完了。