1. 一個const 對象用來管理系統中的變量。
在組件中,當一個組件需要獲取多個狀態時候,將這些狀態都聲明爲計算屬性會有些重複和冗餘。爲了解決這個問題,我們可以使用 mapState
輔助函數幫助我們生成計算屬性。
當映射的計算屬性的名稱與 state 的子節點名稱相同時,我們也可以給 mapState
傳一個字符串數組。
computed: ...mapState(['level','itemNum','itemDetail','timer'
]), 相當於每個 this.level = store.state.level
1.什麼是
mutations
?
-
上一篇文章說的
getters
是爲了初步獲取和簡單處理state
裏面的數據(這裏的簡單處理不能改變
state
裏面的數據),Vue
的視圖是由數據驅動的,也就是說state
裏面的數據是動態變化的,那麼怎麼改變呢,切記在Vuex
中store
數據改變的唯一方法就是mutation
! -
通俗的理解
mutations
,裏面裝着一些改變數據方法的集合,這是Veux
設計很重要的一點,就是把處理數據邏輯方法全部放在mutations
裏面,使得數據和視圖分離。
2.怎麼用
mutations
?
-
mutation結構:每一個
mutation
都有一個字符串類型的事件類型(type
)和回調函數(handler
),也可以理解爲{type:handler()}
,這和訂閱發佈有點類似。先註冊事件,當觸發響應類型的時候調用handker()
,調用type
的時候需要用到store.commit
方法。const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state) { //註冊事件,type:increment,handler第一個參數是state; // 變更狀態 state.count++}}}) store.commit('increment') //調用type,觸發handler(state)
-
載荷(payload):簡單的理解就是往
handler(stage)
中傳參handler(stage,pryload)
;一般是個對象。mutations: { increment (state, n) { state.count += n}} store.commit('increment', 10)
-
mutation-types:將常量放在單獨的文件中,方便協作開發。
// mutation-types.js export const SOME_MUTATION = 'SOME_MUTATION' // store.js import Vuex from 'vuex' import { SOME_MUTATION } from './mutation-types' const store = new Vuex.Store({ state: { ... }, mutations: { // 我們可以使用 ES2015 風格的計算屬性命名功能來使用一個常量作爲函數名 [SOME_MUTATION] (state) { // mutate state } } })
-
commit:提交可以在組件中使用
this.$store.commit('xxx')
提交mutation
,或者使用mapMutations
輔助函數將組件中的methods
映射爲store.commit
調用(需要在根節點注入store
)。import { mapMutations } from 'vuex' export default { methods: { ...mapMutations([ 'increment' // 映射 this.increment() 爲 this.$store.commit('increment')]), ...mapMutations({ add: 'increment' // 映射 this.add() 爲 this.$store.commit('increment') })}}