Vue 资源,使用相同的形式进行插入和更新
Vue resource, using the same form for inserts and updates
我正在使用 Vue 资源连接到我的后端 api。我有一个表单组件,用于创建新资源项和修改现有资源项。表单工作正常,但是当我想保存表单时,它需要为 api 调用使用正确的 http 方法。如果我正在创建一个新项目,它应该使用 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
资源函数,然后 success/fail 承诺都使用相同的代码。有什么方法可以将上面的两种方法与这样的东西结合起来:
var method = this.itemId ? 'PUT' : 'POST';
myresource.request(method, {id: this.itemId}, this.item).then(response => {
//...
}, response => {
//...
});
上面的代码显然行不通,但是有没有类似的方法可以在不使用 if
语句并为每种请求类型重复我的 success/fail 承诺的情况下完成此操作?
一个简单的选择是根据条件创建请求,然后将剩余的承诺连接到一条链中:
const request = (this.itemId > 0) ? myresource.update ? myresource.save;
request({
id: this.itemId // Make the save call ignore the id
}, this.item).then(response => {
// Shared code
});
我正在使用 Vue 资源连接到我的后端 api。我有一个表单组件,用于创建新资源项和修改现有资源项。表单工作正常,但是当我想保存表单时,它需要为 api 调用使用正确的 http 方法。如果我正在创建一个新项目,它应该使用 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
资源函数,然后 success/fail 承诺都使用相同的代码。有什么方法可以将上面的两种方法与这样的东西结合起来:
var method = this.itemId ? 'PUT' : 'POST';
myresource.request(method, {id: this.itemId}, this.item).then(response => {
//...
}, response => {
//...
});
上面的代码显然行不通,但是有没有类似的方法可以在不使用 if
语句并为每种请求类型重复我的 success/fail 承诺的情况下完成此操作?
一个简单的选择是根据条件创建请求,然后将剩余的承诺连接到一条链中:
const request = (this.itemId > 0) ? myresource.update ? myresource.save;
request({
id: this.itemId // Make the save call ignore the id
}, this.item).then(response => {
// Shared code
});