vue实现购物车的基本功能
功能:
1.对书籍数量的增减
2.对书籍的移除
这里对于价格后面的2位小数用到了过滤器,对于价格的¥符号也一起过滤。
对于总价格的计算,方法有跟多,我也写了一些,我这里显示的效果用的是reduce。
上代码。。。。。
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../css/购物车.css" />
<title></title>
</head>
<body>
<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="(book,index) in Books">
<!-- <td v-for="bookValue in book">{{bookValue}}</td> -->
<td >{{book.name}}</td>
<td >{{book.date}}</td>
<td >
<!-- {{getFinalPrice(book.price)}} -->
{{book.price | showFinalPrice}}
</td>
<td >
<button @click="decrement(index)" :disabled="book.count<=1">-</button>
{{book.count}}
<button @click="increment(index)">+</button>
</td>
<td>
{{book.count}}
</td>
<td>
<button @click="remove(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<h2>总价:{{allPrice | showFinalPrice}}</h2>
</div>
<h2 v-else>还没有选购哦!</h2>
</div>
<script src="../js/vue.js"></script>
<script src="../js/购物车.js"></script>
</body>
</html>
js
const app =new Vue({
el:"#app",
data:{
Books:[
{
id:1,
name:"高数",
date:"2021.3.21",
price:45.00,
count:1
},
{
id:2,
name:"化学",
date:"2021.3.24",
price:94.00,
count:1
},
{
id:3,
name:"物理",
date:"2021.3.23",
price:73.00,
count:1
},
{
id:4,
name:"英语",
date:"2021.3.22",
price:85.00,
count:1
}
]
},
methods:{
increment(index){
this.Books[index].count++;
},
decrement(index){
if(this.Books[index].count!=1)
this.Books[index].count--;
},
remove(index){
this.Books.splice(index,1)
}
/* getFinalPrice(price){
return '¥'+price.toFixed(2)
} */
},
filters:{
showFinalPrice(price){
return '¥'+price.toFixed(2)
}
},
computed:{
allPrice(){
let allPrice=0;
/* for(let i=0;i<this.Books.length;i++){
allPrice+=this.Books[i].count * this.Books[i].price;
} */
/* for(let i in this.Books){
allPrice+=this.Books[i].count * this.Books[i].price;
} */
/* for( let book of this.Books){
allPrice += book.price * book.count;
}
return allPrice; */
return this.Books.reduce(function(preValue,Books){
return preValue + Books.price *Books.count;
},0)
}
}
});
css
table{
border: 1px solid #000000;
border-collapse: collapse;
border-spacing: 0;
}
th,td{
padding: 8px 16px;
border: 1px solid #c1bcbc;
text-align: center;
}
th{
background-color: #f0ed94;
color: #000000;
font-weight: 600;
}
over…