Vue02-小案例(购物车功能)
效果图
主要代码
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> table { border-collapse: collapse; /* text-align: center; */ } thead { background-color: #f5f5f5; } th, td { border: 1px solid #aaa; padding: 8px 16px; } .active { background-color: skyblue; } </style> </head> <body> <div id="app"> <template v-if="books.length"> <table> <thead> <tr> <th>序号</th> <th>书籍名称</th> <th>出版日期</th> <th>价格</th> <th>购买数量</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="(book,index) in books" :key="index" @click="liClick(index)" :class="{active : index===currentIndex }"> <td>{{book.id}}</td> <td>{{book.name}}</td> <td>{{book.date}}</td> <td>{{formatPrice(book.price)}}</td> <td> <button :disabled="book.count <= 1" @click="countMinus(index)"> - </button> {{book.count}} <button @click="countAdd(index)">+</button> </td> <td> <button @click="removeBook(book,index)">删除</button> </td> </tr> </tbody> </table> <h2>总价:{{formatPrice(total)}}</h2> </template> <template v-else> <h2>当前购物车数量为空!</h2> </template> </div> <script src="vue.js"></script> <script src="data.js"></script> <script> const app = Vue.createApp({ data() { return { books, currentIndex:0 } }, computed: { total() { // 1. 遍历books let price = 0 for (const item of this.books) { price += item.price * item.count } return price } }, methods:{ formatPrice(price){ return '¥' + price }, countAdd(bookId){ this.books[bookId].count ++ }, countMinus(bookId){ this.books[bookId].count -- }, removeBook(book,index){ this.books.splice(index, 1) }, liClick(index){ this.currentIndex = index } }, }) app.mount('#app') </script> </body> </html>
数据文件
data.js
const books = [ { id: 1, name: '《算法导论》', date: '2006-9', price: 85.00, count: 1 }, { id: 2, name: '《UNIX编程艺术》', date: '2006-2', price: 59.00, count: 1 }, { id: 3, name: '《编程珠玑》', date: '2008-10', price: 39.00, count: 1 }, { id: 4, name: '《代码大全》', date: '2006-3', price: 128.00, count: 1 }, { id: 5, name: '《你不知道JavaScript》', date: '2014-8', price: 88.00, count: 1 }, ]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」