【问题标题】:Vue: Wait until parent function is finished runningVue:等到父函数完成运行
【发布时间】:2020-11-12 12:00:28
【问题描述】:

我正在调用父函数,但之后我的 axios 调用在父函数完成之前触发。有没有办法在这里使用 Promise 以便在我的 axios post 调用之前先解析父函数?

let data = {
   name: "Charles"
   age:  44
}

this.$parent.updateInfo(data);

axios.post('/admin/setup/change', {
    status: "new",
    comment: this.newNotes,
})

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    如果$parent.updateInfo 是异步的,你可以这样做:

    this.$parent.updateInfo(data)
      .then(() => {
        axios.post('/admin/setup/change', {
          status: "new",
          comment: this.newNotes,
        });
      })
      .catch(error => {
        console.log(error.message);
      })
    
    

    那么你可以确定axios.post会在$parent.updateInfo之后被调用

    【讨论】:

    • 有趣...在 updateInfo 内部是一个 axios 调用。我仍然可以像在孩子身上那样使用then()
    • updateInfo return Promise 这样你就可以在这个 Promise 上使用 .then 来处理这个 Promise 的结果。阅读此内容应该可以帮助您理解: - What is promise - handling promise with .then
    • 您也可以使用await,这会使代码更清晰,但是您要调用此await $parent.updateInfoawait axios.post 的方法必须是异步的(async)。 async & await
    【解决方案2】:

    您可以使用 async/await,因此代码将等待直到进一步执行。

    顺便说一句,我不认为this.$parent.updateInfo(data); 是从父范围触发函数的常用方法。我更愿意向父实例发出一个事件,正如这里所建议的https://stackoverflow.com/a/46208765/11377556

    【讨论】:

      猜你喜欢
      • 2019-11-14
      • 1970-01-01
      • 2019-09-01
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 2015-09-16
      • 2019-11-25
      相关资源
      最近更新 更多