<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>元件之子元件使用$on與$emit事件觸發父元件實現購物車功能</title>
<script src="vue.js"></script>
</head> <body>
<div id="hdcms">
<hd-news :listdata="goods" @sum="total"></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" @blur="sums"><!--失去焦點之後觸發子元件繫結的事件-->
</td>
</tr>
</table>
</script>
<script>
var hdNews = {
template: "#hdNews",
props: ['listdata'],//繼承父元件的資料
methods: {
sums() {
this.$emit('sum');//@emit的作用就是子元件呼叫父元件的事件
}
}
};
new Vue({
el: "#hdcms",
components: {hdNews},
mounted() { //當vue執行完畢之後,去執行函式
this.total();
},
data: {
totalPrice: 0,
goods: [{
name: '蘋果X',
price: 200,
num: 1
},
{
name: '華為P10',
price: 100,
num: 1
},
{
name: '小米6',
price: 50,
num: 1
},
]
},
methods: {
total() {
this.totalPrice = 0;
this.goods.forEach((v) => {
this.totalPrice += v.num * v.price;
});
}
}
});
</script> </body> </html>