实战:利用计算属性、指令等知识开发购物车
源码地址
购物车需要展示 一个己加入购物车的商品列表,包含商品名称、商品单价、购买数量和操作等信息,还需要实时显示购买的总价。其中购买数量可以增加或减少,每类商品还可以从购物车中移除。也能添加商品到购物车中,最后一项是否选中该商品的功能,总价变为只计算选中商品的总价 实现效果如下:
购物车
table{
border: 1px solid #e9e9e9;
border-collapse: collapse;
border-spacing: 0;
empty-cells: show;
}
th, td {
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: left;
}
th {
background: #f7f7f7;
color: #5c6b77;
font-weight: 600;
white-space: nowrap;
}
商品名称:
商品单价:
购买数量:
添加
商品名称
商品单价
购买数量
操作
是否选择
{{ index + 1 }}
{{ item.name }}
{{ item.price }}
-
{{ item.count }}
+
移除
总价 {{ totalPrice }} 元
购物车为空
var app = new Vue({
el: "#app",
data: {
list : [
{
id : 1,
name : "iPhone 7",
price : '6666',
count : 1,
select:true
},
{
id : 2,
name : "iPhone 7 pro",
price : '8888',
count : 1,
select:true
},
{
id : 3,
name : "iPad",
price : '7658',
count : 1,
select:true
},
],
name:'',
price:'',
count:''
},
computed: {
totalPrice : function() {
var s = 0;
for(let i = 0; i
this.list[index].count = this.list[index].count == 1 ? 1 : this.list[index].count-1;
},
Add(index) {
this.list[index].count += 1;
},
Remove(index) {
this.list.splice(index, 1);
},
newAdd(){
this.list.push(
{
id : this.list.length,
name : this.name,
price : this.price,
count : this.count,
select: true
}
)
}
}
})
|