<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>vue综合练习</title>
<style type="text/css">
td{
align-content: center;
}
</style>
</head>
<body>
<div id="app">
<h3>购物车</h3>
<h4 v-if="products.length==0">空空如也</h4>
<div v-else>
<table border="1" cellspacing="0" align="center">
<tr>
<th>编号</th>
<th>商品名称</th>
<th>商品价格</th>
<th>商品数量</th>
<th>操作</th>
</tr>
<tr v-for="(product,index) in products">
<td>{{index+1}}</td>
<td>{{product.name}}</td>
<td>{{product.price}}</td>
<td><button @click="reduce(index)">-</button>{{product.num}}<button @click="add(index)">+</button></td>
<td><button @click="del(index)">删除</button></td>
</tr
<tr>
<td colspan="5">总价:{{total}}</td>
</tr>
</table>
</div>
</div>
<script type="text/javascript" src="vue.js" ></script>
<script>
var app = new Vue({
el: "#app",
data: {
products:[
{id:1,name:"西瓜",price:20.00,num:4},
{id:2,name:"牛奶",price:30.00,num:2},
{id:3,name:"榴莲",price:80.00,num:1}
],
total:0
},
methods:{
del (index) {
this.products.splice(index,1);
this.count();
},
reduce (index) {
if(this.products[index].num>0){
this.products[index].num--;
this.count();
}
},
add (index){
this.products[index].num++;
this.count();
},
count () {
this.total=0;
for(var i in this.products){
this.total+=this.products[i].price*this.products[i].num;
}
}
},
mounted(){
this.count();
}
});
</script>
</body>
</html>
|