《Vue.j实战》一书 p54 页练习1和练习2:
练习1 : 在当前示例基础上扩展商品列表,新增一项是否选中该商品的功能,总价变为只计算选中商品的总价,同时提供一个全选的按钮。
练习2 : 将商品列表list 改为一个二维数组来实现商品的分类,比如可分为“电子产品”“生活用品”和“果蔬” ,同类商品聚合在一起。提示,你可能会用到两次v -for。
Demo浏览地址:https://sx00xs.github.io/test/46/index.html
文件格式:.vue
<template> <div id="app"> <template v-if="list.length"> <table> <thead> <tr> <th></th> <th>商品类别</th> <th>商品名称</th> <th>商品单价</th> <th>购买数量</th> <th>操作</th> <th>是否选中</th> <th> <button @click="handleSelectall">{{message}}</button> </th> </tr> </thead> <tbody> <template v-for="(item, index) in list"> <tr v-for="(subitem, subindex) in item" :key="subitem.ke"> <td>{{subitem.id}}</td> <td>{{subitem.category}}</td> <td>{{subitem.name}}</td> <td>{{subitem.price}}</td> <td> <button @click="handleReduce(index,subindex)" :disabled="subitem.count === 1">-</button> {{subitem.count}} <button @click="handleAdd(index,subindex)">+</button> </td> <td> <button @click="handleRemove(index,subindex)">移除</button> </td> <td> <input type="checkbox" v-model="subitem.isChecked"> </td> </tr> </template> </tbody> </table> <div>总价:¥ {{ totalPrice }}</div> </template> <div v-else>购物车为空</div> </div> </template> <script> export default { data(){ return{ message:'全选', list:[ [ { id:1, category:'电子产品', ke:'a', name:'iPhone 7', price:6188, count:1, isChecked:true }, { id:2, category:'电子产品', ke:'b', name:'iPad Pro', price:5888, count:1, isChecked:true }, { id:3, category:'电子产品', ke:'c', name:'MacBook Pro', price:21488, count:1, isChecked:true } ], [ { id:4, category:'生活用品', ke:'d', name:'牙膏', price:29, count:1, isChecked:true }, { id:5, category:'生活用品', ke:'e', name:'纸巾', price:19, count:1, isChecked:true }, { id:6, category:'生活用品', ke:'f', name:'衣架', price:33, count:1, isChecked:true } ], [ { id:7, category:'果蔬', ke:'g', name:'苹果', price:13, count:1, isChecked:true }, { id:8, category:'果蔬', ke:'h', name:'葡萄', price:25, count:1, isChecked:true }, { id:9, category:'果蔬', ke:'i', name:'西红柿', price:5, count:1, isChecked:true } ], ] } }, computed:{ totalPrice(){ var total = 0; for(var i=0;i<this.list.length;i++){ for(var j=0;j<this.list[i].length;j++){ var item = this.list[i][j]; if(item.isChecked){ total += item.price * item.count; } } } return total.toString().replace(/B(?=(d{3})+$)/g,','); } }, methods:{ handleReduce(index,subindex){ if(this.list[index][subindex].count === 1) return; this.list[index][subindex].count--; }, handleAdd(index,subindex){ this.list[index][subindex].count++ }, handleRemove(index,subindex){ //this.list.splice(index,1); this.list[index].splice(subindex,1); }, handleSelectall(){ for(var i=0;i<this.list.length;i++){ for(var j=0;j<this.list[i].length;j++){ this.list[i][j].isChecked=true; } } } } } </script>