【发布时间】:2018-02-22 09:28:26
【问题描述】:
我正在使用 Vue 资源连接到我的后端 api。我有一个表单组件,用于创建新资源项和修改现有资源项。表单工作正常,但是当我想保存表单时,它需要使用正确的 http 方法进行 api 调用。如果我正在创建一个新项目,它应该使用POST 方法,如果我正在更新一个现有项目,它应该使用PUT 方法。现在,我的表单保存方法看起来像这样:
if(this.itemId > 0) { // Update existing item
myresource.update({id: this.itemId}, this.item).then(response => {
//...
}, response => {
//...
});
}
else { // Post new item
myresource.save({}, this.item).then(response => {
//...
}, response => {
//...
});
}
基本上,我必须使用if 语句来检查是否使用update 或save 资源函数,然后成功/失败承诺都使用相同的代码。有没有办法将上述两种方法与这样的方法结合起来:
var method = this.itemId ? 'PUT' : 'POST';
myresource.request(method, {id: this.itemId}, this.item).then(response => {
//...
}, response => {
//...
});
上面的代码显然不起作用,但是是否有类似的方法可以在不使用if 语句并为每种请求类型重复我的成功/失败承诺的情况下完成此操作?
【问题讨论】:
标签: api vue.js vue-resource