购物车结算 案例
这是做出来的效果:
案例要求:
如果两样商品的金额(不含运费)合计超过了5000元,则可减免100元
如果两样商品的金额(不含运费)合计超过了8000元,则可减免200元
在如上五个输入框中修改数值时,各项统计结果要实时更新
以下是我的代码:
<template> <div> <h2>购物车结算案例</h2> <hr> <div class="div"> <table> <tr> <td>手机:</td> <td>价格 <input type="text" v-model.number="price1"></td> <td>数量 <input type="text" v-model.number="num1"></td> <td>小记 {{sum1}}元</td> </tr> <tr> <td>电脑:</td> <td>价格 <input type="text" v-model.number="price2"></td> <td>数量 <input type="text" v-model.number="num2"></td> <td>小记 {{sum2}}元</td> </tr> </table> <div class="conter"> <div>运费: <input type="number" v-model.number="fare"></div> <p>总计: {{sum1+sum2}}</p> <p>优惠: {{youhui}}</p> <p>应付: {{sum}}</p></div> </div> </div> </template> <script> export default { data () { return { price1: 7999, price2: 5888, num1: 2, num2: 1, fare: 10 } }, computed: { sum1 () { return this.price1 * this.num1 }, sum2 () { return this.price2 * this.num2 }, sum () { const a = this.sum1 + this.sum2 if (a > 8000) { return a + this.fare - 200 } else if (a > 5000) { return a + this.fare - 100 } else { return a + this.fare } }, youhui () { const a = this.sum1 + this.sum2 if (a > 8000) { return 200 } else if (a > 5000) { return 100 } else { return 0 } } }, watch: { num1: { deep: true, handler () { if (this.num1 < 1) { this.num1 = 1 } } }, num2: { deep: true, handler () { if (this.num2 < 1) { this.num2 = 1 } } }, fare: { deep: true, handler () { if (this.fare < 10) { this.fare = 10 } } } } } </script> <style scoped> h2{ text-align: center; } input{ width: 70px; } .div{ width: 500px; height: 400px; margin: 50px auto; border-radius: 5%; line-height: 40px; background-color: rgb(255, 255, 255); box-shadow: 2px 3px 5px #888888; } td{ padding: 0 15.7px; } .conter{ padding: 10px; } </style>复制代码
购物车选商品时是不允许数量少于1的,在每个价格栏增加watch监听,一旦数据小于1则让改数据等于1
作者:啦啦啦啦啦啦啦啦
链接:https://juejin.cn/post/7014667733799272478