<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>
<style>
.menu {
width: 600px;
border-top: 1px solid #999;
border-left: 1px solid #999;
border-spacing: 0; /*去掉单元格间隙*/
margin: auto; /*居中*/
}
.menu td {
padding: 10px 20px 30px 30px;
border-bottom: 1px solid #999;
border-right: 1px solid #999;
}
.menu th {
padding: 10px 20px;
background-color: #c0c0c0;
border-bottom: 1px solid #999;
border-right: 1px solid #999;
}
p,
h2 {
text-align: center;
}
</style>
</head>
<body>
<div id="app" v-cloak>
<div v-if="boolean">
<table class="menu">
<thead>
<th>序号</th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</thead>
<tbody>
<tr v-for="(item,index) in books">
<td>{{index+1}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{item.price}}</td>
<td>
<button @click="sub(index)" :disabled="item.count<=1">-</button>
{{item.count}}
<button @click="add(index)">+</button>
</td>
<td>
<button @click="removeHandle(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<h2>总价格:{{totalPrice}}</h2>
</div>
<p v-else>购物车被你清空了</p>
</div>
<script src="https://unpkg.com/vue@3"></script>
<script>
//app的实例对象
const app = Vue.createApp({
//组件数据
data() {
return {
books: [
{
id: 1,
name: "《算法导论》",
date: "2006-9",
price: 85,
count: 1,
},
{
id: 2,
name: "《UNIX编程艺术》",
date: "2006-2",
price: 59,
count: 1,
},
{
id: 3,
name: "《编程珠玑》",
date: "2008-10",
price: 39,
count: 1,
},
{
id: 4,
name: "《代码大全》",
date: "2006-3",
price: 128,
count: 1,
},
],
boolean: true,
};
},
//组件方法
methods: {
add(index) {
this.books[index].count++;
},
sub(index) {
this.books[index].count--;
},
removeHandle(index) {
this.books.splice(index, 1);
if (this.books.length == 0) {
this.boolean = false;
}
},
},
computed: {
totalPrice() {
var sum = 0;
for (i = 0; i < this.books.length; i++) {
sum += this.books[i].price * this.books[i].count;
}
return sum;
},
},
});
//组件挂载
app.mount("#app");
</script>
</body>
</html>
小练习 vue购物车
最新推荐文章于 2024-05-22 16:17:56 发布