2016-04-02 68 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裏面,有人告訴我這是不正確的...所以我改變它,現在我想現在如果現在可以= = –