如何在按钮上连续调用函数@click [VUE JS]

Ost*_*nko 0 javascript promise vue.js

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

<CButton
  @click=" getBillPrice();
           updateBill();
           postData();"
  type="submit"
  color="primary">Save</CButton>
Run Code Online (Sandbox Code Playgroud)

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

我该如何解决?这是我的一些功能。这是能够发布这么多代码的文本,您可以跳过此文本:Lorem ipsum dolor sat amet、consectetur adipiscing elit、sed do eiusmod tempor incididunt ut laboure 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。例外 sint occaecat cupidatat non proident, 在 culpa qui offcia 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________*/
    },
Run Code Online (Sandbox Code Playgroud)

Moh*_*shi 7

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

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

Run Code Online (Sandbox Code Playgroud)

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

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

  },
  ...
}
Run Code Online (Sandbox Code Playgroud)

由于您的项目似乎不支持 async await,您可以试试这个。(我在 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
    })

  },
  ...
}
Run Code Online (Sandbox Code Playgroud)