<div id="app">
<boy></boy>
</div>
<script src="js/vue.js"></script>
<script>
Vue.component("boy",{
template:`
<girl v-bind:love="fruit"></girl>
`,
data:function(){
return{
fruit:[
{name:"香蕉",price:1,num:1,sum:1},
{name:"蘋果",price:2,num:1,sum:2},
{name:"鴨梨",price:3,num:1,sum:3}
]
}
}
});
Vue.component("girl",{
props:["love"],
template:`
<table border="1" cellspacing="0" width="860px">
<tr>
<th>編號</th>
<th>名稱</th>
<th>單價</th>
<th>數(shù)量</th>
<th>總價</th>
</tr>
<tr v-for="(value,index) in love">
<td>{{index+1}}</td>
<td>{{value.name}}</td>
<td>{{value.price}}</td>
<td>
<button @click='add(index)'>+</button>
{{value.num}}
<button @click='att(index)'>-</button>
</td>
<td>{{value.sum}}</td>
</tr>
<td colspan="5">總計:¥{{total}}</td>
</table>
`,
data:function(){
return{
total:0
}
},
methods:{
add:function(ind){
this.love[ind].num++;
this.love[ind].sum = this.love[ind].num*this.love[ind].price;
this.tot()
},
att:function(ind){
if(this.love[ind].num>1){
this.love[ind].num--;
}
this.love[ind].sum = this.love[ind].num*this.love[ind].price;
this.tot()
},
tot:function(){
for(var i= 0,skr=0;i<this.love.length;i++){
skr+=this.love [i].sum
}
this.total = skr
}
}
});
new Vue({
el:"#app"
});
</script>
QQ截圖20180920112910.png