30.Action

Vuex的Action,相当於component内的methods,里面宣告并使用方法,但不会直接改变资料状态。

Action 类似于 mutation,不同在于:
Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作。

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

action也能写成:

actions: {
  //依照ES2015 
  increment ({ commit }) {
    commit('increment')
  }
}

Action Dispatch
Action 通过 store.dispatch 方法触发:

store.dispatch('increment')

可以在 action 内部执行异步操作:

actions: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}
// 以载荷形式分发
store.dispatch('incrementAsync', {
  amount: 10
})

// 以对象形式分发
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

在component使用dispatch action
用 mapActions 辅助函数将component的 methods 映射为 store.dispatch 调用:

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')`
    })
  }
}

<<:  Day 30 最终章:结语与初心

>>:  结语

为什麽我的流程图都让工程师很头痛?

在这篇开始之前想到一个小故事... 业务工程师: 我把流程都给你了,你们应该可以很快做完吧? 工程师...

[DAY 07]查询各国物品名称

昨天写完查询物品拍卖价格网址後发现...既然都有各国物品名称了 乾脆多做一个查询各国物品名称并附上W...

SQL Server VM 常见的 CPU 设定问题 - 心得分享

DBA Bootcamp 前一阵子,发现一台 SQL Server 的 compute 效能好像不如...

[Day02] 变数

变数 变数是用来储存资料和进行基本运算的基本单位;在宣告时给资料一个名称,名称像一个盒子把资料装起来...

Day11:终於要进去新手村了-Javascript-变数与运算子简单的综合运用

这里就记录一下前两篇变数与运算子综合运用的方式,做个简单练习。 下面就写一个简单的乘法计算,最近刚好...