练习一
要求:用组件的方法实现点击加或减按钮时数量、加减、总计也随之加减
模拟购物车.png
代码如下
<div id="app">
<my-main></my-main>
</div>
<script src="../9.19/js/vue.js"></script>
<script>
Vue.component('my-main',{
template:`
<div class="container">
<table class="table table-bordered text-center" border="1">
<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>
<my-tr v-bind:arrs="list"></my-tr>
</table>
</div>
`,
data:function(){
return{
list:[
{pname:'apple',price:3,count:2,sub:6},
{pname:'pear',price:4,count:3,sub:12},
{pname:'banana',price:5,count:4,sub:20}
]
}
}
})
Vue.component('my-tr',{
props:['arrs'],
template:`
<tbody>
<tr v-for="(value,index) in arrs">
<td>{{index+1}}</td>
<td>{{value.pname}}</td>
<td>{{value.price}}</td>
<td>
<button @click='add(index)'>+</button>
<span>{{value.count}}</span>
<button @click='redu(index)'>-</button>
</td>
<td>{{value.sub}}</td>
</tr>
<tr>
<td colspan="5">总价:¥{{sum}}</td>
</tr>
</tbody>
`,
data:function(){
return{
sum:38
}
},
methods:{
add:function(ind){
//数量
this.arrs[ind].count++;
//改变小计
this.arrs[ind].sub=this.arrs[ind].count*this.arrs[ind].price;
this.total();
},
redu:function(ind){
//数量
if(this.arrs[ind].count>0){
this.arrs[ind].count--;
}
//小计
this.arrs[ind].sub=this.arrs[ind].count*this.arrs[ind].price;
this.total();
},
total: function () {
for (var i = 0, tota = 0; i < this.arrs.length; i++) {
tota += this.arrs[i].sub
}
this.sum = tota
}
}
})
new Vue({
el:'#app'
})
</script>
练习二
要求:用组件的方法实现在心input中输入内容点击添加按钮可在arr后添加,点击删除可删除内容
Image 1.png
代码如下:
<div id="app">
<my-mother></my-mother>
</div>
<script src="js/vue.js"></script>
<script>
Vue.component('my-mother',{
template:`
<div>
<input type="text" v-model="obj">
<button v-on:click="but">添加</button>
<my-name v-bind:arrs="arr"></my-name>
</div>
`,
data:function(){
return{
arr:["吃饭","睡觉","打豆豆"],
obj:''
}
},
methods:{
but:function(){
this.arr.push(this.obj)
this.obj=''
}
}
})
Vue.component('my-name',{
props:['arrs'],
template:`
<ul>
<li v-for="(value,index) in arrs">{{value}}<button v-on:click="shan(index)">删除</button></li>
</ul>
`,
methods:{
shan:function(index){
this.arrs.splice(index,1)
}
}
})
new Vue({
el:'#app'
})
</script>