2016-04-02 70 views
1

解决this problem感谢@nils后,此问题出来了,我希望有人能帮助我!HTTP请求删除记录,然后从数组中删除obj Vue.js

其实我有一个记录列表,我可以选择一些然后删除那些只需点击一下。

上面的代码正常工作,但我不知道我所做的是正确的还是它可以打破任何时间!

所以我在做HTTP请求删除Array.filter()内部的记录......是吗?我觉得这是不对的!

deleteSelected() { 
    this.list = this.list.filter(function(val, i) { 
    var id = val.id.toString(); 

    if (this.selected.indexOf(id) === -1) { 
     return true; 
    } else { 

     this.$http.delete('/sources/' + id) 
     .then(function() { 
      return false; 
     }, function() { 
      return true; 
     }); 

    } 
    }, this); 

    this.selected = []; 
}, 

阵列this.list是其中是我的对象的列表和this.selected数组包含ID的选择以被去除。

然后,如果HTTP请求确定我删除obj,如果没有,我保留它!

您认为这是一个好方法吗?

--------- ---------编辑

添加JSBin要清楚我需要什么!

其实我只是在脚本中发现了一个问题......它不会等待ajax响应从数组中删除项目,所以如果某些记录不能删除,它将从阵列以及

有人?

JS Bin

回答

0

正如我虽然代码不起作用,但我找到了一个很好的解决方案!

它不工作,因为它是一个批量删除,所以每个删除是一个请求,但我已经让所有人一次,脚本不会等待答案从列表中删除该项目!如果记录最终没有通过验证被删除,它也会从列表中删除!

所以我做的是发送所有删除请求,当最后一个完成时,我提出一个新的请求,以获得更新的整个列表!

下面是代码:

// block the records list 
$(this.$els.dataGrid).block(); 

// init a counter 
var itemsProcessed = 0; 

// get length of records to be deleted 
var length = this.selected.length; 

// looping to delete one for each 
this.selected.forEach((item) => { 

    // removeLossReasonById() is a method that mand the HTTP DELETE request and then() 
    this.removeLossReasonById(item).then((response) => { 

    // if does not delete for any reason show a notify 
    if (!response.ok) 
     $.Notification.error(response.data); 

    // increment the counter 
    itemsProcessed++; 

    // if is the last iteration it's gonna unblock the records list and clear my array of items to be removed 
    if (itemsProcessed === length) { 
     this.selected = []; 
     this.getLossReasons().then(() => $(this.$els.dataGrid).unblock()); 
    } 
    }); 
}); 

希望它可以帮助别人!

2

我做的是一样的东西:

<ul> 
    <li v-for="item in list" @click="deleteItem(item)"></li> 
</ul> 

所以你基本上是通过列表项的删除方法,这反过来做:即解决

deleteItem: function(item) { 
    # Ajax delete request 
    .successs(
     this.list.$remove(item); 
    ) 

贵问题?

+0

这不是我需要立人!我只是添加了一个JS Bin来清除我需要的东西!看,如果你知道该怎么做! –

+0

现在无法对其进行测试,但我确实尝试删除您的ajax请求,并使代码正常工作。因此,可能要查看该请求的后端上发生了什么。 – Liren

+0

是的!但是,因为我在这个前端框架的新东西,我想知道这是否是正确的方式。我之前把它放在一个FOR LOOPING里面,有人告诉我这是不正确的...所以我改变它,现在我想现在如果现在可以= = –