Vue-购物车案例
需求
实现购物车效果
- 修改数量, 总价格会实时计算
- 点击按钮移除书籍
代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script src="./node_modules/vue/dist/vue.global.js"></script> <style> * { margin: 0; padding: 0; } #app { margin: 50px; width: 500px; height: 250px; border: 2px dashed black; } table { border: 2px, solid, black; width: 480px; height: 160px; line-height: 25px; margin: auto; } th, td { border: 1px, solid, black; } #totalprice { text-align: right; } </style> </head> <body> <div id="app"> <table> <caption>购物车</caption> <thead> <tr> <th></th> <th>书籍名称</th> <th>出版日期</th> <th>价格</th> <th>购买数量</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="(product, index) in products" :key="product.id"> <td>{{ index + 1 }}</td> <td>{{ product.name }}</td> <td>{{ product.date }}</td> <td>¥{{ product.price.toFixed(2) }}</td> <td> <button @click="reduceQuantity(index)">-</button>{{ product.quantity}}<button @click="addQuantity(index)">+</button> </td> <td> <button @click="removeProduct(index)">移除</button> </td> </tr> </tbody> <tfoot> <tr> <td colspan="6" id="totalprice">总价格: ¥{{ totalprice.toFixed(2) }}</td> </tr> </tfoot> </table> </div> <script> const { createApp } = Vue const vm = createApp({ data() { return { products: [ { id: 1, name: '算法导论', date: '2006-09', price: 85.00, quantity: 2 }, { id: 2, name: 'Unix编程艺术', date: '2006-02', price: 59.00, quantity: 2 }, { id: 3, name: '编程珠玑', date: '2008-10', price: 39.00, quantity: 2 } ] } }, computed: { totalprice() { return this.products.reduce( (total, product) => { return total + product.price * product.quantity; }, 0) } }, methods: { removeProduct(index) { this.products.splice(index, 1); }, reduceQuantity(index) { if (this.products[index].quantity > 1) { this.products[index].quantity-- } }, addQuantity(index) { this.products[index].quantity++ }, } }).mount('#app') </script> </body> </html>
本文作者:khrushchefox
本文链接:https://www.cnblogs.com/khrushchefox/p/18573274
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步