经过一番学习vue的基础知识, 利用计算属性、指令等知识开发一个简易的前端小项目,购物车
实现效果如下图所示:
不多说了 直接展示代码
html文件
<!DOCTYPE html> <html> <head lang="en"> <link rel="stylesheet" href="css/shoppingCar.css"/> <link rel="stylesheet" href="bootstrap/css/bootstrap.css"/> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script> <div id="shoppingCar"> <template> <table class="table"> <thead> <tr> <th>序号</th> <th>商品名称</th> <th>商品单价</th> <th>购买数量</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="(item,idnex) in list"> <td> {{item.id}} </td> <td> {{item.name}} </td> <td> {{item.price}} </td> <td> <button @click="jian(idnex)">-</button> {{item.count}} <button @click="jia(idnex)">+</button> </td> <td> <button @click="del()">删除</button> </td> </tr> </tbody> </table> <span>总价:¥</span>{{sum}} </template> <!-- <template v-else> <span>购物车为空</span> </template> --> </div> <script src="js/shoppingCar.js"></script> <script src="bootstrap/js/bootstrap.min.js"></script> <script src="bootstrap/js/jquery.min.js"></script> </body> </html>js 代码:
var vue = new Vue({ el:'#shoppingCar', data:{ status:1, list:[ { id:1, name:'iPhone7', price:6188, count:1 }, { id:2, name:'iPhone8', price:7188, count:1 }, { id:1, name:'iPhoneXS', price:8188, count:1 } ] }, computed:{ sum: function(){ var total = 0; for(var i = 0 ; i<this.list.length;i++){ var totalone = this.list[i].price * this.list[i].count; total = total+totalone; } return total.toString().replace(/\B(?=(\d{3})+$)/g,''); } }, methods:{ jian : function(index){ if(this.list[index].count==0){ return; } this.list[index].count-- ; }, jia : function(index){ this.list[index].count++ ; }, del: function(index){ this.list.splice(index,1); } } })css代码:
table{ border: 1px soild #e9e9e9; border-collapse: collapse; border-spacing :0; empty-cells:show; } th, td{ padding :8px 16px; border:1px soild #e9e9e9; text-align:left; } th{ background: #f7f7f7; color:#5c6b77; font-weight:600; white-space:nowrap; }喜欢或者对你有帮助 点个? - 。- vue