感觉自己有时候学新的东西就会忘记之前学过的。
Vue实现一个购物车,主要实现了增加数量,减少数量,移除数据,结算等功能,完成图如下:

主要说一下思路:
1.使用一个数组作为一个图书信息的一个整合,展示直接for循环展示
2.图书数量的增加可以无限,但是减少到1就停止,去掉减少这个按钮,可以使用v-if
3.移除按钮,直接删除掉数组中的整个对象,按钮,考虑方法methods
4.结算,当前的数组中所有价格和数量的乘积总和,因为是一个数值,所以考虑计算属性computed
首先是HTML,引入vue
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<div id="app">
<h2>购物车</h2>
<table v-if="this.books.length != 0">
<tr v-for="(item,index) in books" :key="index">
<td>{{item.book_name}}</td>
<td>¥{{item.book_price}}</td>
<td>
<span @click="item.count++">+</span>
{{item.count}}
<span @click="item.count--" v-if="item.count > 1">-</span>
</td>
<td>
<button @click="remove(index)">移除</button>
</td>
</tr>
</table>
<p>结算:{{result}}</p>
</div>
css样式,可不看
table{
border:1px solid #e9e9e9;
border-collapse:collapse;
border-spacing:0;
}
th,td{
padding:8px;
border:1px solid #e9e9e9;
text-align:center;
}
th{
background:#f7f7f7;
color:#5c6b77;
font-weight:600;
}
span{
cursor:pointer;
}
js
new Vue({
el: '#app',
data:{
books:[
{
book_name:'图书1',
book_price:12,
count:1
},
{
book_name:'图书2',
book_price:30,
count:1
},
{
book_name:'图书3',
book_price:52,
count:1
}
]
},
computed:{
result(){
var result = 0;
this.books.map(x => result += x.book_price*x.count);
return result;
}
},
methods:{
remove:function(index){
this.books.splice(index,1);
}
}
})
补充一个有小数点的数字,一般金额都精确到点的后两位。单数
filters:{
pricePoint(price){
return price.toFixed(2);
}
}
HTML模板
<td>¥{{item.book_price | pricePoint}}</td>
<p>结算:{{result | pricePoint}}</p>
本文详细介绍了使用Vue.js实现购物车功能的过程,包括商品数量增减、移除、结算等功能,通过具体代码示例展示了如何操作数组来更新视图,并使用计算属性进行总价计算。

1万+

被折叠的 条评论
为什么被折叠?



