HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>购物车</title>
<link rel="stylesheet" href="./index.css">
<script src="../vue.js"></script>
<script src="./index.js"></script>
</head>
<body>
<div id="order" >
<div v-if = "array.length">
<table>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for = "(arr,index) in array">
<td>{{arr.id}}</td>
<td>{{arr.name}}</td>
<td>{{arr.time}}</td>
<td>{{arr.price | showPrice}}</td>
<td>
<button @click = "decrement(index)" :disabled = "array[index].count <= 1">-</button>
{{arr.count}}
<button @click = "increment(index)">+</button>
</td>
<td><button @click = "removeHandle(index)">移除</button></td>
</tr>
</tbody>
</table>
<h2>总价格:{{totlePrice | showPrice}}</h2>
</div>
<h1 v-else><em>购物车已清空</em></h1>
</div>
</body>
</html>
CSS
#order{
width: 50%;
height: 500px;
margin: 100px auto;
}
table{
width: 100%;
height: 200px;
border: 1px solid #000;
/* 单元格间距 */
border-spacing:0px;
/* 合并单元格 */
border-collapse:collapse;
}
tr,th,td{
border: 1px solid #000;
text-align: center;
}
th{
background-color: rgba(155, 147, 147, 0.171);
}
h2{
display: inline-block;
}
Vue
window.onload = function(){
const app = new Vue({
el:"#order",
data:{
array:[
{
id:1,
name:"《算法导论》",
time:'2006-9',
price:85,
count:1
},
{
id:2,
name:"《UNIX编程艺术》",
time:'2006-2',
price:59,
count:1
},
{
id:3,
name:"《编程珠玑》",
time:'2008-10',
price:39,
count:1
},
{
id:4,
name:"《代码大全》",
time:'2006-3',
price:128,
count:1
}
]
},
methods:{
decrement(index){
return this.array[index].count--
},
increment(index){
return this.array[index].count++
},
removeHandle(index){
this.array.splice(index,1)
}
},
// 过滤器
filters:{
showPrice(price){
return'¥'+price.toFixed(2)
}
},
computed:{
totlePrice(){
let num= 0;
for(let i=0;i<this.array.length;i++){
num+=this.array[i].price * this.array[i].count;
}
return num
}
}
})
}
结果展示
使用Vue做的简单购物车搭建