在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
1.购物车案例经过一系列的学习,我们这里来练习一个购物车的案例
总体效果如下: 2.代码实现<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="../js/vue.js"></script> <style> table{ border: 1px solid #e9e9e9; border-collapse: collapse; border-spacing: 0; } th,td{ padding: 8px 16px; border: 1px solid #e9e9e9; text-align: left; } th{ background-color: #f7f7f7; color: #5c6b77; font-weight: 600; } </style> </head> <body> <div id="app"> <div v-if="books.length"> <table> <thread> <tr> <th></th> <th>书籍名称</th> <th>出版日期</th> <th>价格</th> <th>购买数量</th> <th>操作</th> </tr> </thread> <tbody> <tr v-for="(book, index) in books" :key="book"> <td>{{index+1}}</td> <td>{{book.name}}</td> <td>{{book.publish_date}}</td> <td>{{book.price | showPrice}}</td> <td> <button @click="decrease(index)" :disabled="book.count <= 0">-</button> {{book.count}} <button @click="increase(index)">+</button> </td> <td> <button @click="removeClick(index)">移除</button> </td> </tr> </tbody> </table> <p>总价:{{totalPrice | showPrice}}</p> </div> <h2 v-else>购物车为空</h2> </div> <script> const app = new Vue({ el: "#app", data: { books: [ {"name":"算法导论", "publish_date":"2006-9", "price":20.00, "count": 0}, {"name":"UNIX编程艺术", "publish_date":"2006-2", "price":30.00, "count": 0}, {"name":"编程技术", "publish_date":"2008-10", "price":40.00, "count": 0}, {"name":"代码大全", "publish_date":"2006-3", "price":50.00, "count": 0}, ], }, methods: { // 增加+ decrease(index){ this.books[index].count-=1 }, // 减少- increase(index){ this.books[index].count+=1 }, // 移除按钮 removeClick(index){ this.books.splice(index, 1) } }, computed: { // 计算总价格 totalPrice(){ let totalPrice = 0 for (let item of this.books){ totalPrice += item.price * item.count } return totalPrice } }, // 过滤器,将价格过滤成有2位小数的 filters: { showPrice(price){ return '¥' + price.toFixed(2) } } }) </script> </body> </html> 3.总结v-for:循环,循环 到此这篇关于Vue 购物车案例练习的文章就介绍到这了,更多相关Vue 购物车练习内容请搜索极客世界以前的文章或继续浏览下面的相关文章希望大家以后多多支持极客世界! |
请发表评论