當一個組件需要獲取多個狀態時候,將這些狀態都聲明爲計算屬性會有些重複和冗餘。爲了解決這個問題,我們可以使用 mapState
輔助函數幫助我們生成計算屬性。
// 在單獨構建的版本中輔助函數爲 Vuex.mapState
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// 箭頭函數可使代碼更簡練,es6的箭頭函數,傳入參數是state,返回值是state.count。然後把返回值映射給count,此時調用this.count就是store裏的count值
count: state => state.count,
// 傳字符串參數 'count' 等同於 `state => state.count`
countAlias: 'count',
// 爲了能夠使用 `this` 獲取局部狀態,必須使用常規函數
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
mapState
函數返回的是一個對象。我們如何將它與局部計算屬性混合使用呢?通常,我們需要使用一個工具函數將多個對象合併爲一個,以使我們可以將最終對象傳給 computed
屬性。但是自從有了對象展開運算符(現處於 ECMASCript 提案 stage-4 階段),我們可以極大地簡化寫法:computed: {
localComputed () { /* ... */ },
// 使用對象展開運算符將此對象混入到外部對象中
...mapState({
// ...
})
}
對象擴展運算符:
- <span style="font-size:14px;">let z = { a: 3, b: 4 };
- let n = { ...z };
- n // { a: 3, b: 4 }</span>
當映射的計算屬性的名稱與 state 的子節點名稱相同時,我們也可以給 mapState
傳一個字符串數組。
computed: mapState([ // 映射 this.count 爲 store.state.count 'count' ])
mapMutations和mapActions:
mapMutations/mapActions只是把mutation/action函數綁定到methods裏面,調裏面的方法時正常傳參數。
注意:映射都是映射到當前對象,使用時需要用this來調用。