Vue.js实现价格计算器功能
时间:2021-08-19 09:49:16|栏目:vue|点击: 次
本文实例为大家分享了Vue.js实现价格计算器功能的具体代码,供大家参考,具体内容如下
实现效果:
实现代码及注释:
<!DOCTYPE html> <html> <head> <title>价格计算器</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style type="text/css"> /* 隐藏未编译的数据绑定,直到Vue实例成功加载 */ [v-cloak]{ display: none; } *{ padding: 0; margin: 0; } body{ font: 15px/1.3 "微软雅黑"; color: #545b64; text-align: center; } a, a:visited{ outline: none; color: #389dc1; } a:hover{ text-decoration: none; } section, footer, header, aside, nav{ display: block; } /*------------------------- The order form --------------------------*/ form{ background-color: #d5d5d5; border-radius: 10px; box-shadow: 0 1px 1px #ccc; width: 400px; padding: 35px 45px; margin: 50px auto; box-shadow: 1px 0px 20px #f5f5f5; } form h1{ color:#fff; font-size: 55px; font-family: "微软雅黑" font-weight: normal; line-height:1; text-shadow:2px 3px 0 rgba(0,0,0,0.1); font-weight: normal; } form ul{ list-style:none; color:#fff; font-size:20px; font-weight:bold; text-align: left; margin:20px 0 15px; } form ul li{ padding:15px 30px; background-color:#03c03c; margin-bottom:10px; box-shadow:0 1px 1px rgba(0,0,0,0.1); cursor:pointer; } form ul li span{ float:right; } form ul li.active{ background-color: orange; } div.total{ border-top:1px solid rgba(255,255,255,0.5); padding:15px 30px; font-size:20px; font-weight:bold; text-align: left; color:#fff; text-shadow: 2px 2px 2px rgba(0,0,0,0.1); } div.total span{ float:right; } </style> </head> <body> <!-- v-cloak隐藏所有没有编译过的数据绑定,直到vue实例准备好 --> <form id="main" v-cloak> <h1>价格计算器</h1> <ul> <!-- 循环这个服务数组,分配一个点击句柄,并且设置或移除active class --> <li v-for="service in services" v-on:click="toggleActive(service)" v-bind:class="{'active': service.active}"> <!-- 显示这个数组中每个实体的名称和价格格式化, Vue有一个内置的货币筛选器用于对价格进行 --> {{service.name}} <span>{{service.price | currency}}</span> </li> </ul> <div class="total"> <!-- 计算所有选定商品的总价格,并且格式化为货币显示方式 --> 总价: <span>{{total() | currency}}</span> </div> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.5/vue.min.js"></script> <script type="text/javascript"> // 定义一个常规过滤器currency Vue.filter('currency', function(value){ return '¥' + value.toFixed(2); }); var demo = new Vue({ el: '#main', data: { // 定义model属性,view将会循环 // 通过services数组产生一个li // 定义services每一项的元素 services: [ { name: "网站开发", price: 300, active: true }, { name: "设计", price: 400, active: false }, { name: "一体化整合", price: 250, active: false }, { name: "操作培训", price: 220, active: false } ] }, methods: { toggleActive: function(s){ s.active = !s.active; }, total: function(){ var total = 0; this.services.forEach(function(s){ if(s.active){ total+=s.price; } }); return total; } } }); </script> </body> </html>