最近在学习Vue相关课程,最开始真的有点搞不懂,学习起来很吃力(虽然现在也是),d但通过今天做的小练习,真心觉得vue太友好了,js要十几行代码才能搞定的事,vue几行代码就可以了,不多说,直接把我练习的小案例放上来:
html代码:
<div id="app">
<!--订单列表 -->
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">订单列表</h3>
</div>
</div>
<!-- 表格 -->
<table class="table table-bordered" style='text-align: center'>
<thead>
<tr>
<td>选择</td>
<td>品牌</td>
<td>单价</td>
<td>数量</td>
<td>总价</td>
<td>删除</td>
</tr>
</thead>
<tbody class='table-striped nth-child table-hover'>
<!-- 动态生成列表内容v-for -->
<tr v-for='item in goodlist' :key='item.id'>
<td><input type="checkbox" @click='item.selected=!item.selected'></td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td><span @click='item.num>0?item.num--:0'>-</span>{{item.num}}<span @click='item.num<10?item.num++:10'>+</span></td>
<td>{{item.price*item.num}}</td>
<td><a href="javascript:;" class="btn btn-primary" @click="del(item.id)">删除</a></td>
</tr>
<p>总价: {{total_price}} 元</p>
</tbody>
</table>
</div>
JS代码:
<script>
var vm=new Vue({
el:'#app',
data:{
goodlist:[
{'id':1,'name':'洗洁精','price':80,'num':1,'selected':false},
{'id':2,'name':'洗发水','price':120,'num':1,'selected':false},
{'id':3,'name':'沐浴露','price':50,'num':1,'selected':false},
{'id':4,'name':'洗衣液','price':40,'num':1,'selected':false}
],
totalPrice:''
},
methods:{
//删除数据
del(id){
var index=this.goodlist.some((item,i)=>{
if(item.id==i){
return true;
}
});
this.goodlist.splice(index,1);
}
},
//computed超好用啊
computed:{
'total_price':function(){
this.totalPrice=0;
//在计算总价的时候,由于必须即时变化价格,需要用到computed监听数据,更重要的是需要遍历每一个选中项,把他们求和
for(var i=0;i<this.goodlist.length;i++) {
if (this.goodlist[i].selected) {
this.totalPrice += this.goodlist[i].price*this.goodlist[i].num;
}
}
return this.totalPrice;
}
}
})
</script>
这个小练习中需要注意的事如何确定刷选出被选中的商品,以及将这些选择的商品的价格求和,确定选择项需要利用selected(或者checked),并对每一行进行辩论;computed为我们提供了良好的体验。