vue2x 组合action的应用

组合 action

  1. Action 中通常放的都是异步的请求,如何知道 action 什么时候结束?
  2. 首先,你需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:
举例子
  1. 本页面有个 input 输入框,需要将 input 中的内容传给后台,并且更新 state 中的数据再清楚 input 框中的内容
<input v-mode="text" />
cosnt actions={
  addItem({commit},text) {
    axios.get('/todos',{text:text}).then(res=> {
      commit('addItem',text)
    })
  }
}
export default {
  addItem() {
    //调用addItem
    this.$store.dispatch("addItem", this.text);
    // 这样肯定是先清空input,因为addItem中的axios请求是异步的,会在同步之后执行
    this.text = "";
  },
};
2. 解决方法:
方法一、
  1. 将 this.text=""以函数的方式传递给 action,action 在 commit 之后执行
cosnt actions={
  addItem({commit},payload) {
    axios.get('/todos',{text:payload.text}).then(res=> {
      commit('addItem',payload.text)
      payload.callback()
    })
  }
}
//调用addItem
this.$store.dispatch("addItem", {
  text: this.text,
  callback: () => (this.text = ""),
});
方法二
  1. action 中返回一个 promise 实例,在 promise 中确定 this.text=’'的执行时机
const actions = {
  addItem({ commit }, text) {
    return new Promise((resolve) => {
      axios.get("/todos", { text: payload.text }).then((res) => {
        commit("addItem", payload.text);
        resolve();
      });
    });
  },
};
//调用addItem
this.$store.dispatch("addItem", this.text).then((res) => {
  this.text = "";
});
方法三
  1. 利用 await 在 async 执行完后执行原理
const actions = {
  async addItem({ commit }, text) {
    axios.get("/todos", { text: payload.text }).then((res) => {
      commit("addItem", payload.text);
    });
  },
};
export default {
  methods:{
     async addItem() {
      await this.$store.dispatch('addItem',this.text)//等待actions中的addItem完成
      this.text=""
    }
  }
}
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值