Vue02-小案例(购物车功能)

效果图

image-20230525000044196

主要代码

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
},
]
posted @   子不语2015831  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示