天天看點

vuex05Action與mapAction

Action是什麼

Action 送出的是 mutation,而不是直接變更狀态。

當然Action也擷取state,getter

Action 可以包含任意異步操作。

Action 函數接受一個與 store 執行個體具有相同方法和屬性的 context 對象,是以你可以調用 context.commit 送出一個 mutation,或者通過 context.state 和 context.getters 來擷取 state 和 getters。

const store = new Vuex.Store({
    state: {
        name: "old name",
        age: 18,
        sex: "女",
    },
    mutations: {
        changName(state) { 
            state.name = "newName"   
        },
        addAge(state, num) {
            state.age += num
        },
        changSex(state) {
            state.sex = state.age + "男"
        }
    },
    actions: {
        useActionToChangName(context) {
        // 這裡的context也可以寫成{commit,state}
            context.commit('changName')
            context.commit('addAge',10)
        }
    }
})      

使用Dispatch來觸發事件

methods: {
    changeNameAndAge() {
      this.$store.dispatch({ type: "useActionToChangName" });
    },
    或者
     changeNameAndAge() {
      this.$store.dispatch ("useActionToChangName" );
    },
}      

mapActions

  1. 引入
import { mapActions } from 'vuex'      
  1. 使用
methods: {
    ...mapActions([
      'useActionToChangName', // 将 `this.useActionToChangName()` 映射為 `this.$store.dispatch('useActionToChangName')`
      // `mapActions` 也支援載荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射為 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'useActionToChangName' // 将 `this.add()` 映射為 `this.$store.dispatch('useActionToChangName')`
    })
  }      

繼續閱讀