043——VUE中组件之使用.sync修饰符与computed计算属性实现购物车原理

时间:2022-01-25 19:25:58
<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>组件之使用.sync修饰符与computed计算属性实现购物车原理</title>
<script src="vue.js"></script>
</head> <body>
<div id="hdcms">
<hd-news :listdata.sync="goods"></hd-news><!--@sum的作用是把父組件的事件綁定到子組件中-->
<h2>总价:{{totalPrice}}</h2>
</div>
<script typeof="text/x-template" id="hdNews">
<table border="2" bordercolor="black" cellspacing="0" cellpadding="20">
<tr>
<td>商品名称</td>
<td>价格</td>
<td>数量</td>
</tr>
<tr v-for="(v,k) in listdata">
<td>{{v.name}}</td>
<td>{{v.price}}</td>
<td>
<input type="text" v-model="v.num"><!--失去焦点之后触发子组件绑定的事件-->
</td>
</tr>
</table>
</script>
<script>
var hdNews = {
template: "#hdNews",
props: ['listdata'],//继承父组件的数据
};
new Vue({
el: "#hdcms",
components: {hdNews},
computed:{
totalPrice(){
var sum=0;
this.goods.forEach((v) => {
sum += v.num * v.price;
});
return sum;
}
},
data: {
goods: [{
name: '苹果X',
price: 200,
num: 1
},
{
name: '华为P10',
price: 100,
num: 1
},
{
name: '小米6',
price: 50,
num: 1
},
]
}
});
</script> </body> </html>