首页 > 解决方案 > 如何在 Vue.js 中的 .then() .catch() 之前使用 if else?

问题描述

我正在 Vue.js 中创建应用程序。我有两种类似的方法:

    editTool() { 
      return ToolService.editTool(this.id, this.editedItem)
        .then((response) => {
          this.$refs.dialogInfo.setSuccess(response);
        })
        .catch((error) => {
          this.$refs.dialogInfo.setError(error);
        })
        .finally(() => {
          this.$emit("completed");
        });
    },

    newTool() {
      return ToolService.addTool(this.editedItem)
        .then((response) => {
          this.$refs.dialogInfo.setSuccess(response);
        })
        .catch((error) => {
          this.$refs.dialogInfo.setError(error);
        })
        .finally(() => {
          this.$emit("completed");
        });
    },

它们只是回报的价值不同,其余的都是一样的。我想把这两种方法合二为一。我试过这样:

    newMethod() {
      if (this.edit) return ToolService.editTool(this.id, this.editedItem);
      else
        return ToolService.addTool(this.editedItem)
          .then((response) => {
            this.$refs.dialogInfo.setSuccess(response);
          })
          .catch((error) => {
            this.$refs.dialogInfo.setError(error);
          })
          .finally(() => {
            this.$emit("completed");
          });
    },

但它不正确。怎么做?

标签: vue.jsif-statementvue-component

解决方案


Try in the following way.

editTool() {
    return ToolService.editTool(this.id, this.editedItem)
  },

  newTool() {
    return ToolService.addTool(this.editedItem)
  },

  newMethod() {
    let method = this.newTool;
    if (this.edit) method = this.editTool;
    return method().then((response) => {
        this.$refs.dialogInfo.setSuccess(response);
      })
      .catch((error) => {
        this.$refs.dialogInfo.setError(error);
      })
      .finally(() => {
        this.$emit("completed");
      });
  }


推荐阅读