vuex實踐之路——筆記本應用(三)
阿新 • • 發佈:2017-07-03
lang 們的 res tool method note 做到 筆記 not ,
Actions
Action 類似於 mutation,不同在於:
- Action 提交的是 mutation,而不是直接變更狀態。
- Action 可以包含任意異步操作。
讓我們來註冊一個簡單的 action,實踐中,我們會經常會用到 ES2015 的 參數解構 來簡化代碼(特別是我們需要調用 commit
很多次的時候):
actions: {
increment ({ commit }) {
commit(‘increment‘)
}
}
看下我們項目中的actions:
怎麽在組件中分發事件呢?
看下我們的Toolbar.vue代碼
首先引入mapActions
輔助函數將組件的 methods 映射為 store.dispatch
映射 addNote() 為 this.$store.dispatch(‘addNote‘),對應actions中的addNote。
使用actions的優點不只在於簡化代碼,更重要的在於我們可以在 action 內部執行異步操作。
mutation 有必須同步執行這個限制。Action 就不受約束:
actions: { incrementAsync ({ commit }) { setTimeout(() => { commit(‘increment‘) }, 1000) } }
這是mutation無法做到的。
至此我們的整個應用已經完成。
附上完整項目github地址
vuex實踐之路——筆記本應用(三)