Vue-购物车简单案例
效果图:
代码部分:
index.html
<div id="app">
<div 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="(item,index) in books">
<td>{{item.id}}</td>
<td>{{item.bookName}}</td>
<td>{{item.date}}</td>
<td>{{item.price | showPrice}}</td>
<td>
<button @click="decrement(index)" :disabled="item.count<=1">-</button>
{{item.count}}
<button @click="increment(index)">+</button>
</td>
<td>
<button @click="removeClick(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<h2>总价格:{{getTotalPrice | showPrice}}</h2>
</div>
<div v-else>
<h2>购物车为空</h2>
</div>
</div>
<script src="../js/vue.js"></script>
<link rel="stylesheet" href="style.css">
<script src="main.js"></script>
main.js
const app = new Vue({
el: '#app',
data: {
books: [
{
id: 1,
bookName: '《算法导论》',
date: '2006-9',
price: 85.00,
count: 1
}, {
id: 2,
bookName: '《UNIX编程艺术》',
date: '2006-2',
price: 59.00,
count: 1
}, {
id: 3,
bookName: '《编程珠玑》',
date: '2008-10',
price: 39.00,
count: 1
}, {
id: 4,
bookName: '《代码大全》',
date: '2006-3',
price: 128.00,
count: 1
},
]
},
computed: {
getTotalPrice() {
// let result = 0;
// for(let i = 0;i<this.books.length;i++){
// result += this.books[i].count*this.books[i].price
// }
// return result;
return this.books.reduce((a,b)=>a+b.price*b.count,0)
}
},
methods: {
// getFinalPrice(price) {
// return '¥'+price.toFixed(2)
// }
increment(index) {
this.books[index].count++;
},
decrement(index) {
this.books[index].count--;
},
removeClick(index) {
this.books.splice(index,1)
}
},
filters: {
showPrice(price) {
return '¥'+price.toFixed(2)
}
}
})
style.css
#app table {
text-align: center;
width: 500px;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!