vue-vuex-actions的基本使用

  之前也讲过了,actions中是用来操作异步代码的,由于在mutations写异步操作会导致devtools工具记录不到state的变化,因此才有actions的存在,下面是基本的使用,如下:

  点击按钮,发布到actions:

<template>
  <div>
    <button @click="toAjax">发起异步请求</button>
  </div>
</template>

methods: {
    toAjax(){
      this.$store.dispatch('sendAjax')
    }
  }

  定义sendAjax,并提交到mutations:

  mutations: {
    msendAjax(state){
      state.counter++
    }
  }
  actions: {
    sendAjax(context){
        //异步操作
      setTimeout(()=>{
        context.commit('msendAjax')
      },1000)
    }

  }

  上面的context对象相当于state,拥有一些和state相同的方法。上面只是基本的使用,如果在dispatch要传递参数,和commit传递参数要怎么做呢?如下:

 methods: {
    toAjax(){
      const arg = '我是参数'
      this.$store.dispatch('sendAjax',arg)
    }
  }
 
  mutations: {
    msendAjax(state,payload){
      console.log(payload)
      state.counter++
    }
  },
  actions: {
    sendAjax(context,arg){
      setTimeout(()=>{
        context.commit('msendAjax',arg)
      },1000)
    }
  }

  上面是actions无参和有参的基本使用了。但实际开发中,在actions中方法执行完毕了,要给componnet返回结果告诉操作已经完成,那该如何做呢? 如下:

<template>
  <div>
    <button @click="toAjax">发起异步请求</button>
  </div>
</template>
methods: {
    toAjax(){
      const arg = '我是参数'
      this.$store
      .dispatch('sendAjax',arg)
      .then(() => {
        console.log('dispatch已经完成了')
      })
    }
  }
  mutations: {
    msendAjax(state,payload){
      console.log(payload)
      state.counter++
    }
  },
  actions: {
    sendAjax(context,arg){
      return new Promise(resolve => {
        setTimeout(()=>{
          context.commit('msendAjax',arg)
          resolve()
        },1000)
      })
    }
  }

  参数该怎么传还怎么传,原本的异步代码用 new Promise包裹起来,然后.then不要在actions中写,在components写会比较明显易懂

原文地址:https://www.cnblogs.com/ibcdwx/p/14641350.html