首页 > 解决方案 > 如何在按钮@click [VUE JS]上连续调用函数

问题描述

我在@click 上调用了 3 个函数,我这样做:

<CButton
  @click=" getBillPrice();
           updateBill();
           postData();"
  type="submit"
  color="primary">Save</CButton>

重要的是首先调用 getBillPrice(),然后是 updateBill(),然后是 postData()。但是这个函数的运行顺序错误,首先运行的是 updateBillPrice 然后是 postData() 然后是 getBillPrice()

我该如何解决?这是我的一些功能。这是能够发布这么多代码的文本,您可以跳过此文本:Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incidudunt ut labore et dolore magna aliqua。Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat。Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur。Exceptioneur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est labourum。

getBillPrice() {
  if (this.data.billid.trim() == "Please Select") {
    return;
  }
  /*getting data from bill*/
  axios
    .get(this.APIServer + "bills/" + this.data.billid, {
      headers: { Authorization: this.$store.state.token },
    })
    .then((response) => {
      if (response.status === 200) {
        this.data.billPrice = response.data.netPrice;
        this.data.billTaxClass = response.data.taxClass;
        this.data.billPriceTotal = response.data.totalPrice;
        console.log("got the get");
      }
    })
    .catch((e) => {
      console.log("API failed");
      console.log(e);
    });
  /*END________*/
},


updateBill() {
  if (
    this.data.amount.trim() == "" ||
    this.data.price.trim() == "" ||
    this.data.title.trim() == "" ||
    this.data.billid.trim() == "Please Select"
  ) {
    return;
  }
  /*Update bill query */
  let updateData = {
    netPrice: Number(this.data.billPrice) + Number(this.data.totalPrice),
    totalPrice:
      (Number(this.data.billPrice) + Number(this.data.totalPrice)) *
        Number(this.data.taxClass) +
      (Number(this.data.billPrice) + Number(this.data.totalPrice)),
  };
  axios
    .patch(this.APIServer + "bills/" + this.data.billid, updateData, {
      headers: { Authorization: this.$store.state.token },
    })
    .then((response) => {
      if (response.status === 200) {
        console.log("bill updated");
      }
    })
    .catch((e) => {
      console.log("API failed");
      console.log(e);
    });
  /*END________*/
},


postData() {
      if (
        this.data.amount.trim() == "" ||
        this.data.price.trim() == "" ||
        this.data.title.trim() == "" ||
        this.data.billid.trim() == "Please Select"
      ) {
        return;
      }

      /*Post item */
      let postData = {
        amount: Number(this.data.amount),
        bill: {
          id: this.data.billid,
        },
        price: Number(this.data.price),
        title: this.data.title,
        totalPrice: Number(this.data.totalPrice),
      };
      axios
        .post(this.APIServer + "items", postData, {
          headers: { Authorization: this.$store.state.token },
        })
        .then((response) => {
          if (response.status === 201) {
            console.log("item posted");
            this.move("/items");
          }
        })
        .catch((e) => {
          console.log("API failed");
          console.log(e);
        });
      /*END________*/
    },

标签: javascriptvue.jspromise

解决方案


我认为与其将每个函数都放在点击事件上,不如创建一个函数来触发这些函数。

<CButton
  @click="onSubmit"
  color="primary">Save</CButton>
methods: {
  onSubmit(){
    this.getBillPrice();
    this.updateBill();
    this.postData()
  },
  ...
}

如果你的函数是异步的,那么你可以使用 async await 和 try catch

methods: {
  async onSubmit(){
    try{
      await this.getBillPrice();
      await this.updateBill();
      this.postData()
    } catch(err){
      // Handle error.
    }

  },
  ...
}

由于您的项目似乎不支持异步等待,您可以尝试一下。(我在 then catch 方面没有太多经验,但它应该可以工作)

methods: {
  onSubmit(){
    this.getBillPrice()
    .then(() => {
       return this.updateBill()
    })
    .then(() => {
       return this.postData()
    })
    .then(() => {
       // Any other code if needed
    })
    .catch((err) => {
       // Handle error scenario
    })

  },
  ...
}

推荐阅读