实现如下图类似购物车效果,
要求数量不能小于1,不能大于10,
单价和总价要带‘¥’符号,并保留2位小数,
删除最后一条记录后清空表格,并显示‘购物车为空!’。
用到的知识点:
- v-for遍历数组
- @click事件绑定
- methods函数定义
- 计算属性(totalprice)
- 过滤器(priceformatter)
- 动态属性绑定(:disabled)
- v-if,v-else隐藏dom元素
style.css如下:
table {
border: 1px solid #e9e9e9;
border-collapse: collapse;
border-spacing: 0;
}
th, td {
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: center;
}
th {
background-color: #dcdcdc;
color: #5c6b77;
font-weight: 600;
}
main.js如下:
const vue = new Vue({
el:"#app",
data:{
goods: [
{
id: 2020111,
name: '999感冒灵',
price: 25.00,
count: 1
},
{
id: 2020115,
name: '莲花清瘟颗粒',
price: 30.00,
count: 1
},
{
id: 2020118,
name: '维C银翘片',
price: 10.00,
count: 1
}
]
},
filters:{
priceformatter(price){
return '¥'+price.toFixed(2);
}
},
computed:{
totalprice(){
let totalprice=0;
for(let i=0;i<this.goods.length;i++){
totalprice += this.goods[i].price*this.goods[i].count;
}
return totalprice;
}
},
methods:{
add(index){
this.goods[index].count++;
},
sub(index){
this.goods[index].count--;
},
remove(index){
this.goods.splice(index,1);
}
}
})
index.html如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<link href="../css/style.css" rel="stylesheet" />
</head>
<body>
<div id="app">
<div v-if="goods.length>0">
<table>
<thead>
<tr>
<th>商品编号</th>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in goods">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.price|priceformatter}}</td>
<td>
<button @click="sub(index)" :disabled="item.count<=1">-</button>
{{item.count}}
<button @click="add(index)" :disabled="item.count>=10">+</button>
</td>
<td><button @click="remove(index)">删除</button></td>
</tr>
</tbody>
</table>
<p>费用合计:{{totalprice|priceformatter}}</p>
</div>
<p style="color:#f00" v-else>购物车为空!</p>
</div>
<script src="../js/vue.js"></script>
<script src="../js/main.js"></script>
</body>
</html>