使用同步修饰符.sync实现子元素到父元素的通信
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue</title>
<script type="text/javascript" src="vue.js"></script>
</head>
<body>
<div id="app">
<hdcms :lists.sync='goods'></hdcms>
总价:{{total}}
</div>
<script type="text/x-template" id="hdcms">
<table>
<tr>
<th>商品名</th>
<th>价格</th>
<th>数量</th>
</tr>
<tr v-for="(v,k) in lists">
<td>{{v.name}}</td>
<td>{{v.price}}</td>
<td><input type="number" v-model='v.num'></td>
</tr>
</table>
</script>
<script type="text/javascript">
var hdcms = {
template: '#hdcms',
props: ['lists']
}
var app = new Vue({
data: {
goods: [
{
name: '苹果X',
price: 1000,
num: 6
},
{
name: '西瓜',
price: 100,
num: 3
}
]
},
computed: {
total(){
let sum = 0;
this.goods.map((v)=>{
sum += v.price * v.num;
})
return sum;
}
},
components: {hdcms}
}).$mount('#app')
</script>
</body>
</html>