Vuex

1 、輔助函數
 
  • mapState

 ...mapState({
    a: state => state.some.nested.module.a, b: state => state.some.nested.module.b })

簡寫帶空間名稱的字符串html

 
 
...mapState('some/nested/module', {
    a: state => state.a, b: state => state.b })
  • mapActions

  ...mapActions([
    'some/nested/module/foo', // -> this['some/nested/module/foo']()
    selfDefine:'some/nested/module/  bar' // -> this['some/nested/module/bar']()
  ])

簡寫帶空間名稱的字符串vue

 ...mapActions('some/nested/module', [
    'foo', // -> this.foo()
    'bar' // -> this.bar()
  ])

 

建立基於命名空間的組件綁定輔助函數。其返回一個包含 mapState、mapGetters、mapActions 和 mapMutations 的對象。它們都已經綁定在了給定的命名空間上。
 
更好的寫法:
 1 import { createNamespacedHelpers } from 'vuex'
 2 
 3 const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')
 4 
 5 export default {
 6   computed: {
 7     // 在 `some/nested/module` 中查找
 8     ...mapState({
 9       a: state => state.a,
10       b: state => state.b
11     })
12   },
13   methods: {
14     // 在 `some/nested/module` 中查找
15     ...mapActions([
16       'foo',
17       'bar'
18     ])
19   }
20 }

 

action 經過  store.dispatch 方法進行分發:
 
乍一眼看上去感受畫蛇添足,咱們直接分發 mutation 豈不更方便?實際上並不是如此,還記得 mutation 必須同步執行這個限制麼?Action 就不受約束!咱們能夠在 action 內部執行異步操做:
 
 
 mutation 必須同步執行這個限制麼?Action 就不受約束!咱們能夠在 action 內部執行異步操做:
actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }
 
Actions 支持一樣的載荷方式和對象方式進行分發:
// 以載荷形式分發
store.dispatch('incrementAsync', { amount: 10 }) // 以對象形式分發
store.dispatch({ type: 'incrementAsync', amount: 10 })

在組件中分發 Action

你在組件中使用 this.$store.dispatch('xxx') 分發 action,或者使用 mapActions 輔助函數將組件的 methods 映射爲 store.dispatch 調用(須要先在根節點注入 store):vuex

import { mapActions } from 'vuex' export default { // ...
 methods: { ...mapActions([ 'increment', // 將 `this.increment()` 映射爲 `this.$store.dispatch('increment')` // `mapActions` 也支持載荷:
      'incrementBy' // 將 `this.incrementBy(amount)` 映射爲 `this.$store.dispatch('incrementBy', amount)`
 ]), ...mapActions({ add: 'increment' // 將 `this.add()` 映射爲 `this.$store.dispatch('increment')`
 }) } }
 commit 和 dispatch的區別 = 一個異步操做與同步操做的區別。

當你的操做行爲中含有異步操做,好比向後臺發送請求獲取數據,就須要使用action的dispatch去完成了。其餘使用commit便可。異步

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息