Vuex异步操作变更数据

vue yekong 1879℃

Actions用于处理异步任务

如果通过异步操作变更数据,必须通过 Action,而不能使用Mutation,但是在 Action中还是要通过触发Mutation的方式间接变更数据。

在Actions 中不能直接修改 state中的数据,要通过 mutations修改。

dispatch触发

this.$store.dispatch 触发 Actions
store.js

// 定义 Action
const store = new Vuex.store({
  // ...省略其他代码
  mutations: {
    // 只有 mutations中的函数才有权利修改 state。
    // 不能在 mutations里执行异步操作。
    add(state) {
      state.count++
    }
  },
  actions: {
    // 在Actions 中不能直接修改 state中的数据,要通过 mutations修改。
    addAsync(context) {
      setTimeout(() => {
        context.commit('add')
      }, 1000);
    }
  },
})

组件A

// 触发 Action
methods:{
  handle(){
    // 触发 actions 的第一种方式
    this.$store.dispatch('addAsync')
  }
}

mapActions 映射为方法

从Vuex中按需导入 mapActions 函数。

import {mapActions} from 'vuex'

将指定的 actions 函数,映射为当前组件 methods 的方法。

methods:{
  ...mapActions(['subAsync']),
  decrementAsync(){
    this.subAsync()
  }
}

store.js

actions: {
 // 在Actions 中不能直接修改 state中的数据,要通过 mutations修改。
  subAsync(context){
    setTimeout(() => {
      context.commit('sub')
    }, 1000);
  }
}
喜欢 (4)