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 achecked
attribute by default
Demo address
html structure
全部商品
{{ shopping.title }}
¥{{ shopping.money }}
x{{ shopping.shoppingnum }}
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 --; } } } });
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:
Change your thinking, don’t delete, filtering is simpler and more intuitive.
Already solved!
Reference address
Use reverse loop