vuex中mapState、mapMutations、mapAction的理解
阿新 • • 發佈:2022-03-05
當一個元件需要獲取多個狀態時候,將這些狀態都宣告為計算屬性會有些重複和冗餘。為了解決這個問題,我們可以使用mapState
輔助函式幫助我們生成計算屬性。
1 // 在單獨構建的版本中輔助函式為 Vuex.mapState 2 import { mapState } from 'vuex' 3 4 export default { 5 // ... 6 computed: mapState({ 7 // 箭頭函式可使程式碼更簡練,es6的箭頭函式,傳入引數是state,返回值是state.count。然後把返回值對映給count,此時呼叫this.count就是store裡的count值 8 count: state => state.count, 9 10 // 傳字串引數 'count' 等同於 `state => state.count` 11 countAlias: 'count', 12 13 // 為了能夠使用 `this` 獲取區域性狀態,必須使用常規函式 14 countPlusLocalState (state) { 15 return state.count + this.localCount 16 } 17 }) 18 }
mapState函式返回的是一個物件。我們如何將它與區域性計算屬性混合使用呢?通常,我們需要使用一個工具函式將多個物件合併為一個,以使我們可以將最終物件傳給computed屬性。但是自從有了物件展開運算子(現處於 ECMASCript 提案 stage-4 階段),我們可以極大地簡化寫法:
-
1 computed: { 2 localComputed () { /* ... */ }, 3 // 使用物件展開運算子將此物件混入到外部物件中 4 ...mapState({ 5 // ... 6 }) 7 }
物件擴充套件運算子:
-
1 <span style="font-size:14px;">let z = { a: 3, b: 4 }; 2 let n = { ...z }; 3 n // { a: 3, b: 4 }</span>
當對映的計算屬性的名稱與 state 的子節點名稱相同時,我們也可以給mapState
傳一個字串陣列。
-
1 computed: mapState([ 2 // 對映 this.count 為 store.state.count 3 'count' 4 ])
mapMutations和mapActions:
mapMutations/mapActions只是把mutation/action函式繫結到methods裡面,調裡面的方法時正常傳引數。
注意:對映都是對映到當前物件,使用時需要用this來呼叫。
例如:
1 methods:{ 2 ...mapMutations(['login']) 3 } 4 5 6 7 下面使用this.login(data);