【问题标题】:Vue resource, using the same form for inserts and updatesVue 资源,使用相同的形式进行插入和更新
【发布时间】: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 语句来检查是否使用updatesave 资源函数,然后成功/失败承诺都使用相同的代码。有没有办法将上述两种方法与这样的方法结合起来:

var method = this.itemId ? 'PUT' : 'POST';
myresource.request(method, {id: this.itemId}, this.item).then(response => {
        //...
    }, response => {
        //...
    });

上面的代码显然不起作用,但是是否有类似的方法可以在不使用if 语句并为每种请求类型重复我的成功/失败承诺的情况下完成此操作?

【问题讨论】:

    标签: api vue.js vue-resource


    【解决方案1】:

    一个简单的选择是根据条件创建请求,然后将剩余的 Promise 连接到一个链中:

    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
    });
    

    【讨论】:

    • 这看起来应该做得很好。谢谢!
    猜你喜欢
    • 2019-01-07
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    • 2014-01-15
    • 2020-06-12
    相关资源
    最近更新 更多