购物车是table做的,是一个响应式的购物车
[图片上传失败...(image-db9271-1537401916019)]
body:
<div id="app">
<!--我们在写代码或者效果时很容易忘记这个自定义组件名-->
<my-component></my-component>
</div>
js:
<script>
var model=Vue.component('my-component',{
template:
`
<div>
<ttable v-bind:number='arr'></ttable>
</div>
`,
data:function(){
return{
arr:[
{number:1,mc:'apple',dj:14,num:1},
{number:2,mc:'banana',dj:8,num:1},
{number:3,mc:'orange',dj:3,num:1}
]
}
}
})
Vue.component('ttable',{
props:['number'],
template:
`
<div class='container'>
<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>
<tbody>
<tr v-for='(value,index) in number'>
<td>{{value.number}}</td>
<td>{{value.mc}}</td>
<td>{{value.dj}}</td>
<td>
<button @click='add(index)'>+</button>
{{value.num}}
<button @click='delt(index)'>-</button>
</td>
<td>{{(value.dj)*(value.num)}}</td>
</tr>
<tr>
<td colspan='5'>总计:<span>{{total}}</span>元</td>
</tr>
</tbody>
</table>
</div>
`,
data:function(){
return{
total:25
}
},
methods:{
add:function(index){
this.number[index].num++
this.getTotal()
},
delt:function(index){
if(this.number[index].num>1){
this.number[index].num--
}
this.getTotal()
},
getTotal:function(){
for(var i=0,to=0;i<this.number.length;i++){
to+=Number(this.number[i].dj*this.number[i].num)
}
this.total=to;
}
}
})
new Vue({
el: '#app'
})
</script>