vue购物车练习
发布于:2021-12-16 11:26:50
次阅读
<template> <div> <h1>购物车</h1> <table border="1px" cellspacing="0"> <tr> <th></th> <th>编号</th> <th>商品名称</th> <th>价格</th> <th>购买数量</th> <th>操作</th> </tr> <tr v-for="(item,index) in cartList" :key="item.id"> <td><input type="checkbox" v-model="item.checked"></td> <td>{{item.id}}</td> <td>{{item.name}}</td> <td>¥{{item.price}}</td> <td> <button @click="item.count--" :disabled="item.count<=0">-</button> {{item.count}} <button @click="item.count++">+</button> </td> <td><a href="#" @click.prevent="del(index)" >删除</a></td> </tr> <tr> <td colspan="3">总计:</td> <td colspan="3">¥{{totalPrice}}</td> </tr> </table> </div></template><script>export default { name: 'App', data(){ return{ cartList: [ {id:1, checked:false, name:'《细说PHP》', price:10, count:1}, {id:2, checked:false, name:'《细说网页制作》', price:20, count:1}, {id:3, checked:false, name:'《细说JavaScript语言》', price:40, count:1}, {id:4, checked:false, name:'《细说DOM和BOM》', price:50, count:1}, {id:5, checked:false, name:'《细说Ajax与jQuery》', price:60, count:1}, {id:6, checked:false, name:'《细说HTML5高级API》', price:70, count:1}, ] } }, methods:{ del(id){ this.cartList.splice(id,1) } }, computed: { totalPrice(){ let sum =0 for(let item of this.cartList) { console.log(item) if(item.checked) { sum += item.price * item.count; } } return sum; } },}</script><style> h1 { text-align: center; margin-bottom: 20px; } table{ margin: 0 auto; } button{ margin: 0 5px; }</style>