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')`
    })
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章