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>
本文来自博客园,作者:wellplayed,转载请注明原文链接:https://www.cnblogs.com/wellplayed/p/17954662
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了