javascript - Ask: How to delete selected array elements in Vue (when there are multiple selections)?
我想大声告诉你
我想大声告诉你 2017-05-19 10:35:09
0
3
1002

The data is simulated. When clicking edit, I want to delete the selected elements. That is, if one is selected, one will be deleted. If multiple are selected, multiple will be deleted. In this way,
every time Elements in an array have acheckedattribute by default

Demo address

html structure

全部商品

{{ showtext ? '编辑' : '完成' }}

js code

var vm = new Vue({ el : ".t-root", data : { showtext : true, shoppingList : [ { id : 11, title : '贡牌茶叶西湖春茶正宗雨前龙井茶礼盒装礼盒装160g礼盒装', money : 48, imgsrc : 'images/download-order-img-11@2x.png', shoppingnum : 1, checked : true }, { id : 22, title : '贡牌茶叶西湖春茶正宗雨前龙井茶礼盒装礼盒装160g礼盒装', money : 98, imgsrc : 'images/download-order-img-11@2x.png', shoppingnum : 1, checked : true }, { id : 33, title : '贡牌茶叶西湖春茶正宗雨前龙井茶礼盒装礼盒装160g礼盒装', money : 148, imgsrc : 'images/download-order-img-11@2x.png', shoppingnum : 1, checked : true } ] }, computed : { }, methods : { editorShopping : function(){ this.showtext = !this.showtext; }, removeShopping : function(){ var that = this; that.shoppingList.forEach(function(value,index){ //只有为true时才删除 if (value.checked) { that.shoppingList.splice(index,1); // console.log(index); } }); }, add : function(index){ var shopping = this.shoppingList[index]; if (shopping.shoppingnum == 100) { return false; }else { shopping.shoppingnum ++; } }, reduce : function(index){ var shopping = this.shoppingList[index]; if (shopping.shoppingnum == 1){ return false; }else { shopping.shoppingnum --; } } } });
我想大声告诉你
我想大声告诉你

reply all (3)
伊谢尔伦

When deleting array elements in batches in JS, you should delete them in reverse order (meaning to delete elements with a large index first, and then delete elements with a small index),
Because the index of the array will change during the deletion process, if the small elements are deleted first , the index of subsequent elements will change.
I wrote a simple demo:

     

  • {{value}}

    我想大声告诉你

    Change your thinking, don’t delete, filtering is simpler and more intuitive.

    // 直接过滤更简单,直观 var arr = [{a:1,c:true},{a:2,c:false},{a:3,c:true}] arr = arr.filter(function(i){ return !i.c }) console.log(arr) // {a:2,c:false}
      黄舟

      Already solved!
      Reference address
      Use reverse loop

      removeShopping : function(){ var that = this; for (var i = that.shoppingList.length - 1;i >= 0;i--) { var index = that.shoppingList[i]; if (index.checked) { that.shoppingList.splice(i,1); } } }
        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!