今天学习了下vue,跟着教程做了一个实例, 分享给大家一起学习。
讲解一下思路:
1.所有的数据都存在一个数组中,
services:[
{
name:'汉堡包',
price:300,
active:false
},
{
name:'薯片',
price:200,
active:false
},
{
name:'可乐鸡肉块',
price:800,
active:false
},
{
name:'肉卷小甜甜',
price:500,
active:false
}
]
2.使用v-for=“services in services” 循环生成一个 li标签,其中标签之中分别输出 services.name ,services.price,services.active 等值
这个时候就会得到如图
3.制作点击变色
在
- 中加入一个class 和 @click事件,做切换active状态
-
<li :class="{ifactive:services.active}" >
然后设置ifactive{background:#e35885} //设置背景颜色
此时点击li的时候 就会产生变色, 但是这个时候 下方的总价是没有变化的。
4.总价的计算方法:
使用vue的computer属性来计算total值,代码如下total(){ var sum=0; this.services.forEach(function(e){ if(e.active){ sum+=e.price } }) return sum; }
这段代码的意思就是:使用forEach()循环找出数组中active==true的数据,然后使用
sum+=e.price 求出总和5.在li元素中加入切换services.active的methods事件
<li @click="toggleactive(services)"></li>
vue中methods函数如下
new Vue({ el:"#main", data:{}, methods:{ toggleactive(e){ e.active=!e.active } } })
这样子就达到了取反的效果, 点一下是选择,在点一下就是不选中。 然后触动computer事件计算出结果
这里贴出完整的代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>购物车实例2</title> <script src="https://unpkg.com/vue/dist/vue.js"></script> <style type="text/css"> .liactive{ background-color: #e35885 !important; } #main{ width: 700px; border:1px solid #3399EE; position: absolute; background-color: #61a1bc; } #main ul{ padding: 0; } #main h1{ margin: 10px auto; width: 100%; text-align: center; font-size: 60px; font-weight:800; color: #fff; } #main ul li{ list-style-type: none; margin:5px 10px; padding:15px 30px; font-size: 26px; font-weight:900; color: #fff; position: relative; width: 400px; margin: 10px auto; background-color: #8ec16d; border-radius: 5px; } #main ul li span{ float: right; width: 100px; text-align: right; margin-left: 100px; } #main ul:after{ content: ''; border-bottom: 1px solid #fff; width: 450px; display: block; margin: 30px auto; } .total{ display: block; font-size: 30px; font-weight: 900; color:#fff; text-align: left; margin-left: 130px; margin-bottom: 100px; } .total span{ float: right; margin-right: 150px; } </style> </head> <body> <div id="app"> <form id="main"> <h1>Service</h1> <ul> <li :class="{liactive:service.active}" v-for="service in services" @click=toggleActive(service)> {{service.name}}<span>{{service.price | currency}}</span> </li> </ul> <div class="total"> Total:<span>{{total() | currency}}</span> </div> </form> </div> <script type="text/javascript"> new Vue({ el:"#main", data:{ services:[ { name:'汉堡包', price:300, active:false }, { name:'薯片', price:200, active:false }, { name:'可乐鸡肉块', price:800, active:false }, { name:'肉卷小甜甜', price:500, active:false } ] }, methods:{ toggleActive(item){ item.active=!item.active }, total(){ var sum=0; this.services.forEach(function(e){ if(e.active){ sum+=e.price } }) return sum; } }, filters:{ currency:function(value){ return '$'+value.toFixed(2); } } }) </script> </body> </html>
南宁才聚软件专业做小程序开发定制,欢迎一起学习交流:www.zkelm.com