表单由三个部分组成:表单头部、产品清单、产品总价
1、表单使用组件shop_list构建
shop_list 组件中用到的方法有:
sum(),用于计算出产品清单的合计价格
2、其中产品清单的每一行可直接组件shop_item,利用v-for进行渲染,故可在组件shop_list中嵌套组件shop_item
组件shop_item中用到的方法有:
点击 + 按钮调用 add(),增加产品数量,且更新该项产品总价
点击 - 按钮调用 reduce(),减少产品数量(当产品数量等于0时,不再递减),且更新该项产品总价
mounted钩子函数中,利用props接收父级传入的产品信息,算出产品总价(总价=单价*数量)
<!DOCTYPE html>
<html>
<head>
<title>shop_list</title>
<!-- <script src="https://unpkg.com/vue"></script> -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style>
.shop_list th,
.shop_list td {
border: 1px solid #eee;
text-align: center;
}
</style>
</head>
<body>
<div id='app'>
<shop_list :pro_list='pro_list'></shop_list>
</div>
<script>
Vue.component('shop_list', {
props: ['pro_list'],
template: `<table class='shop_list'>
<thead>
<tr>
<th>编号</th>
<th>名称</th>
<th>价格</th>
<th>数量</th>
<th>总计</th>
</tr>
</thead>
<tbody>
<shop_item v-for="(item,index) in pro_list" :pro_info='item' :key='index' :id='index'></shop_item>
<tr>
<td colspan='5'>合计:{{sum()}}</td>
</tr>
</tbody>
</table>`,
methods: {
//计算出产品清单的合计价格
sum(){
var n=0;
for(var i=0;i< this.pro_list.length;i++){
n+= this.pro_list[i].total;
}
return n;
}
}
});
Vue.component('shop_item', {
props: ["pro_info", "id"],
template: `
<tr>
<td>{{id+1}}</td>
<td>{{pro_info.pName}}</td>
<td>{{pro_info.price}}</td>
<td>
<button @click='add'>+</button>
{{pro_info.num}}
<button @click='reduce'>-</button>
</td>
<td>{{pro_info.price*pro_info.num}}</td>
</tr >`,
methods: {
add: function (even) {
this.pro_info.num++;//增加产品数量
this.pro_info.total = this.pro_info.num * this.pro_info.price;//且更新该项产品总价
},
reduce: function () {
if (this.pro_info.num == 0)
return;
this.pro_info.num--;//减少产品数量(当产品数量等于0时,不再递减) this.pro_info.total = this.pro_info.num * this.pro_info.price;//且更新该项产品总价
}
},
mounted:function(){
this.pro_info.total = this.pro_info.num * this.pro_info.price;//算出产品总价(总价=单价*数量)
}
});
new Vue({
el: '#app',
data: {
pro_list: [
{ 'pName': 'pro1', 'price': 10, 'num': 1, 'total': '' },
{ 'pName': 'pro2', 'price': 20, 'num': 2, 'total': '' },
{ 'pName': 'pro3', 'price': 30, 'num': 3, 'total': '' }
]
}
});
</script>
</body>
</html>