Vue——实现购物车的增减与价格统计
呈现效果:
第一步:引入vue与bootstrap的CDN
<script src="./js/vue.js"></script> <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
第二步:定义id为app的div
<div id="app"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h1 class="text-center">购物车案例</h1> <table class="table table-bordered"> <thead> <tr> <th>商品id</th> <th>商品名</th> <th>商品价格</th> <th>商品数量</th> <th>全选/全不选<input type="checkbox" v-model="checkAll" @change="handleCheckAll"></th> </tr> </thead> <tbody> <tr v-for="good in goodList"> <th scope="row">{{good.id}}</th> <td>{{good.name}}</td> <td>{{good.price}}</td> <td><span class="btn" @click="handleReduce(good)">-</span> {{good.count}} <span class="btn" @click="handleAdd(good)">+</span> </td> <td><input type="checkbox" v-model="checkGoodList" :value="good" @change="handleCheckOne"></td> </tr> </tbody> </table> <hr> <h3>选中的商品:{{checkGoodList}}</h3> <h3>总价格:{{getPrice()}}</h3> </div> </div> </div>
第三步:书写js代码
<script> new Vue({ el: '#app', data: { goodList: [ {id: 1, name: '短袖', price: 99, count: 2}, {id: 2, name: '短裤', price: 39, count: 1}, {id: 3, name: '短裙', price: 189, count: 6}, {id: 4, name: '短袜', price: 8, count: 8}, {id: 5, name: '长筒袜', price: 4, count: 88}, {id: 6, name: '过膝袜', price: 5, count: 90}, ], checkGoodList: [], checkAll: false }, methods: { getPrice() { // 计算选中的总价格 var total = 0 // 循环选中的,计算总价格this.checkGoodList for (var item of this.checkGoodList) { total += item.price * item.count } return total }, handleCheckAll() { if (this.checkAll) { //全选了,将物品列表全部放入 this.checkGoodList = this.goodList } else { //全不选,将列表清空 this.checkGoodList = [] } }, handleCheckOne() { // 如果checkGoodList的长度等于商品总长度,说明全选了,让checkAll =true if (this.checkGoodList.length == this.goodList.length) { this.checkAll = true } else { // 只要长度不相等,都是false this.checkAll = false } }, handleAdd(good) { good.count++ }, handleReduce(good) { if (good.count > 1) { good.count-- } else { alert('不能再少了,受不了了') } } } }) </script>