利用组件父子传值做的购物车
2018-09-20 本文已影响0人
是你的大颖儿
效果图:
gwc.png
html代码:
<div class="container">
<tab></tab>
</div>
js 代码:
<script src="vue.js"></script>
<script>
Vue.component('tab',{
template:`
<table class="table table-bordered text-center">
<thead>
<tr>
<th class="text-center">编号</th>
<th class="text-center">名称</th>
<th class="text-center">单价</th>
<th class="text-center">数量</th>
<th class="text-center">总价</th>
</tr>
</thead>
<chld v-bind:frulit='arr'></chld>
</table>
`,
data:function(){
return{
arr:[
{name:"香蕉",danjia:"8",num:"2",price:"16"},
{name:"苹果",danjia:"5",num:"3",price:"15"},
{name:"鸭梨",danjia:"3",num:"1",price:"3"}
]
}
}
})
Vue.component('chld',{
props:['frulit'],
template:`
<tbody>
<tr v-for="(v,ind) in frulit">
<td>{{ind+1}}</td>
<td>{{v.name}}</td>
<td>{{v.danjia}}</td>
<td>
<button @click="jia(ind)">+</button>
<span>{{v.num}}</span>
<button @click="jian(ind)">-</button></td>
<td>{{v.price}}</td>
</tr>
<tr>
<td colspan="5">总计:{{arrs}}元</td>
</tr>
</tbody>
`,
data:function(){
return{
arrs:34.00
}
},
methods:{
jia:function(ind){
// 数量
this.frulit[ind].num++;
// 小计
this.frulit[ind].price=this.frulit[ind].num*this.frulit[ind].danjia;
this.tal();
},
jian:function(ind){
// 数量
if(this.frulit[ind].num>1){
this.frulit[ind].num--;
// 小计
this.frulit[ind].price=this.frulit[ind].num*this.frulit[ind].danjia;
this.tal();
}
},
// 总价
tal:function(){
for(var i=0,j=0;i<this.frulit.length;i++){
j+=Number(this.frulit[i].price)
}
this.arrs=j
}
}
})
new Vue({
el:".container"
})
</script>