Vuejs学习笔记(一)-15.购物车作业
代码如下:
1 <!-- 2 @author:invoker 3 @project:project_lianxi 4 @file: 05-购物车.html 5 @contact:invoker2021@126.com 6 @descript: 7 @Date:2021/7/1 15:25 8 @version: html5 9 --> 10 11 <!DOCTYPE html> 12 <html lang="en"> 13 <head> 14 <meta charset="UTF-8"> 15 <title>05-购物车</title> 16 </head> 17 <body> 18 <div id="app"> 19 <table v-show="isShow"> 20 <thead> 21 <tr> 22 <th v-for="item in column">{{item}}</th> 23 </tr> 24 </thead> 25 <tbody> 26 <!--1.对象的循环,使用到了item和index--> 27 <tr v-for="(record,index) in books"> 28 <!--2.对象内部元素的循环,使用到了键key和值value的调用--> 29 <td v-for="(value,key) in record"> 30 <!--3.使用到了v-show和key的结合,只要key===nums为true则在界面显示Button--> 31 <!--4.点击按钮则动态增加或减少,按钮监听,decrement(index),传入Index是告诉对象哪个记录的按钮需要加减,从而改变对应的nums--> 32 <!--5.如果购买的数量为0,就不能再继续点击减号,因此使用disabled属性与条件(record.nums是动态的)的动态绑定使用到了v-on--> 33 <button v-show="key==='nums'" @click="decrementClick(index)" :disabled="record.nums<=0">-</button> 34 {{value}} 35 <button v-show="key==='nums'" @click="incrementClick(index)">+</button> 36 </td> 37 <td> 38 <!--7.此处用到了删除记录,详见methods--> 39 <button @click="deleteRecord(index)">删除</button> 40 </td> 41 </tr> 42 <tr> 43 <!--6.此处用到了过滤器,详见Vue实例的选项filters--> 44 <td colspan="5">总价格:{{totalPrice | showPrice}}</td> 45 </tr> 46 </tbody> 47 </table> 48 <div v-show="!isShow"> 49 <h2>空空如也!</h2> 50 </div> 51 </div> 52 53 <script src="../js/vue.js"></script> 54 <script> 55 const app = new Vue({ 56 el: '#app', 57 data: { 58 message: 'hello', 59 books: [ 60 {id: 1, name: '《算法导论》', date: '2018-06', price: 85.00, nums: 0}, 61 {id: 2, name: '《python入门》', date: '2017-06', price: 35.00, nums: 0}, 62 {id: 3, name: '《vue学习》', date: '2014-06', price: 185.00, nums: 0}, 63 {id: 4, name: '《Fastapi入门》', date: '2020-06', price: 89.00, nums: 0}, 64 {id: 5, name: '《pytest学习》', date: '2018-06', price: 85.00, nums: 0}, 65 {id: 6, name: '《selenium学习》', date: '2018-06', price: 65.00, nums: 0}, 66 ], 67 column: [ 68 '编号', '书籍名称', '出版日期', '价格', '购买数量', '操作' 69 ], 70 isShow: true 71 }, 72 methods: { 73 decrementClick(index) { 74 // 只要nums大于0就可以点击,否则不能点击 75 if (this.books[index].nums > 0) { 76 this.books[index].nums-- 77 } 78 79 }, 80 incrementClick(index) { 81 this.books[index].nums++ 82 }, 83 // 删除记录的代码,从数组中删除使用splice方法 84 deleteRecord(index) { 85 this.books.splice(index, 1) 86 } 87 }, 88 // 对于价格总数使用计算属性来实时存储,节约性能 89 computed: { 90 totalPrice() { 91 let total = 0 92 for (let book of this.books) { 93 total += book.price * book.nums 94 } 95 if (this.books.length === 0) { 96 this.isShow = false 97 } 98 return total 99 } 100 }, 101 // 过滤器用于展示总价的样式 102 filters: { 103 showPrice(price) { 104 return "$" + price.toFixed(2) 105 } 106 } 107 }) 108 </script> 109 </body> 110 </html>
本文来自博客园,作者:kaer_invoker,转载请注明原文链接:https://www.cnblogs.com/invoker2021/p/14959479.html