最近在学习Vue相关课程,最开始真的有点搞不懂,学习起来很吃力(虽然现在也是),d但通过今天做的小练习,真心觉得vue太友好了,js要几十行代码才能搞定的事,vue几行代码就可以了,不多说,直接把我练习的小案例放上来:
html代码:
<div id=\"app\">
<!--订单列表 -->
<div class=\"panel panel-primary\">
<div class=\"panel-heading\">
<h3 class=\"panel- \">订单列表</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=\" :;\" class=\"btn btn-primary\" @click=\"del(item.id)\">删除</a></td>
</tr>
<p>总价: {{total_price}} 元</p>
</tbody>
</table>
</div>
JS代码:
< >
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;
}
}
})
</ >
这个小练习中需要注意的事如何确定刷选出被选中的商品,以及将这些选择的商品的价格求和,确定选择项需要利用selected(或者checked),并对每一行进行辩论;computed为我们提供了良好的体验。
继续阅读与本文标签相同的文章
上一篇 :
电脑操作分享:如何创建无法删除的文件夹?
下一篇 :
UG NX参数化建模小练习
-
如何1秒在Word中输入10000+个字?这个功能太强大了!
2026-05-18栏目: 教程
-
三星胜诉!韩专利审判院裁定瑞士龙沙公司专利无效
2026-05-18栏目: 教程
-
随着人类文明的进步科技的发展,技术驱动的顶级问题慢慢浮现!
2026-05-18栏目: 教程
-
GitHub最强技术面试手册:Tech Interview Handbook
2026-05-18栏目: 教程
-
阿里云ACP认证考试须知+心得(精)
2026-05-18栏目: 教程
