<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <style type="text/css"> </style> </head> <body> <div id="app"> <table border="0" cellspacing="" cellpadding="20"> <tr> <th>序号</th> <th>电影名称</th> <th>发行时间</th> <th>电影票价</th> <th>购买数量</th> <th>操作</th> </tr> <tr v-for="(item,index) in movies"> <td>{{index}}</td> <td>{{item.name}}</td> <td>{{item.date}}</td> <td>{{item.money | toFixedMoney}}</td> <td> <button type="button" @click="reduce(index)" :disabled="item.count<=1">-</button> {{item.count}} <button type="button" @click="plus(index)">+</button> </td> <td> <button type="button" @click="cut(index)">删除此行</button> </td> </tr> </table> <h2>共计:{{totaMoney | toFixedMoney}}</h2> </div> <script type="text/javascript"> const vm = new Vue({ el: '#app', data: { movies: [{ name: "蜘蛛侠", date: "2006-9", money: 45.00, count: 1 }, { name: "毒液", date: "2020-2", money: 32.00, count: 1 }, { name: "小猪佩奇", date: "2008-13", money: 20.00, count: 1 }, { name: "长津湖", date: "2021-10", money: 100.00, count: 1 } ], }, methods: { reduce(index) { this.movies[index].count--; }, plus(index) { this.movies[index].count++ }, cut(index) { this.movies.splice(index, 1) } }, computed: { totaMoney() { /* for循环 let total = 0; for (var i = 0; i < this.movies.length; i++) { total += this.movies[i].money * this.movies[i].count } return total; */ // forEach /* let total = 0; this.movies.forEach(item=>{ total += item.money * item.count }) return total */ // for in /* let total = 0; for(let i in this.movies){ total+= this.movies[i].money * this.movies[i].count } return total; */ // forof /* let total = 0; for (let item of this.movies) { total += item.money * item.count } return total; */ // filter /* let total = 0; this.movies.filter((v)=>{ total += v.count *v.money }) return total */ // map /* let total = 0; this.movies.map((v)=>{ total +=v.count * v.money }) return total */ // reduce return this.movies.reduce((currentTotal, item) => { return currentTotal + item.money * item.count }, 0) /* return this.movies.reduce((total, currentValue) => { return total += currentValue.money * currentValue.count }, 0) */ } }, filters: { toFixedMoney: function(money) { let fix = money.toFixed(2); return '¥' + fix } } }) </script> </body> </html>
效果如下:
Vue.filter( id, [definition] )注册或获取全局过滤器。