邂逅Vue3,实现一个简易书籍购物车
效果:
html
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 <title>书籍购物车</title> 9 <link rel="stylesheet" href="./style.css"> 10 </head> 11 12 <body> 13 <template id='cart'> 14 <template v-if='books.length > 0'> 15 <table> 16 <thead> 17 <th>序号</th> 18 <th>书籍名称</th> 19 <th>出版日期</th> 20 <th>价格</th> 21 <th>购买数量</th> 22 <th>操作</th> 23 </thead> 24 <tbody> 25 <tr v-for='(book,index) in books'> 26 <td>{{index + 1}}</td> 27 <td>{{book.name}}</td> 28 <td>{{book.date}}</td> 29 <td>{{formatPrice(book.price)}}</td> 30 <td> 31 <button @click='decrement(index)'>-</button> 32 {{book.count}} 33 <button @click='increment(index)'>+</button> 34 </td> 35 <td> 36 <button @click='removeBook($emit,index)'>移除</button> 37 </td> 38 </tr> 39 </tbody> 40 </table> 41 <h2 id = 'totalPrice'>总计:{{formatPrice(totalPrice)}}</h2> 42 </template> 43 <template v-else> 44 <h2>这里什么都没有了哦~~</h2> 45 </template> 46 47 </template> 48 <div id="cartContainer"></div> 49 <script src="./vue.js"></script> 50 <script src="./index.js"></script> 51 </body> 52 53 </html>
js
1 Vue.createApp({ 2 template: '#cart', 3 data() { 4 return { 5 books: [ 6 { 7 id: 1, 8 name: '《算法导论》', 9 date: '2006-9', 10 price: 85.00, 11 count: 1 12 }, 13 { 14 id: 2, 15 name: '《UNIX编程艺术》', 16 date: '2006-2', 17 price: 59.00, 18 count: 1 19 }, 20 { 21 id: 3, 22 name: '《编程珠玑》', 23 date: '2008-10', 24 price: 39.00, 25 count: 1 26 }, 27 { 28 id: 4, 29 name: '《代码大全》', 30 date: '2006-3', 31 price: 128.00, 32 count: 1 33 }, 34 ] 35 } 36 }, 37 methods:{ 38 removeBook(event,index){ 39 this.books.splice(index,1); 40 }, 41 decrement(index){ 42 this.books[index].count--; 43 }, 44 increment(index){ 45 this.books[index].count++; 46 }, 47 formatPrice(price){ 48 var newPrice = '¥'+price; 49 return newPrice 50 } 51 }, 52 computed:{ 53 totalPrice(){ 54 var totalPrice = 0; 55 this.books.forEach(item => { 56 totalPrice += item.price * item.count; 57 }); 58 return totalPrice 59 } 60 } 61 }).mount('#cartContainer')
css
1 table { 2 border: 1px solid #e9e9e9; 3 border-collapse: collapse; 4 border-spacing: 0; 5 } 6 7 th, td { 8 padding: 8px 16px; 9 border: 1px solid #e9e9e9; 10 text-align: left; 11 } 12 13 th { 14 background-color: #f7f7f7; 15 color: #5c6b77; 16 font-weight: 600; 17 } 18 19 .counter { 20 margin: 0 5px; 21 }
保持好奇,保持学习,做时间的朋友