vue.js - 如何在 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");
});
},
但它不正确。怎么做?
解决方案
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");
});
}
推荐阅读
- openlayers - Openlayers:从请求中加载坐标数据
- delphi - Delphi,在 where 条件中带有 DetailFields 的 Master-Detail(不在选择部分中)
- azure-timeseries-insights - Azure 时序见解的底层数据库/存储是什么?
- java - Java/Android:在数组中解析没有单个字符串的 JSON
- react-native - 在没有 aws amplify 的情况下在博览会 ImagePicker 中上传图像
- javascript - javascript文件的浏览器缓存失效而不更改src URL
- spring-data-jpa - Spring with Querydsl:java.lang.ClassCastException
- r - 使用 ggplotly 的地图显示不正确(R)
- excel - 选中一个框会取消选中 Excel 中的相邻框
- java - 如何使用 Spring Boot 和 MongoDB 生成 8 位唯一编号?