本文实例讲述了vue基于两个计算属性实现选中和全选功能。分享给大家供大家参考,具体如下:
还是选中和全选功能,用两个计算属性来实现,别人的代码,思维确实不一样。学习了
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>www.gxlcms.com vue选中和全选</title> <style> table, td, th{ border:1px solid #ebebeb; border-collapse:collapse; text-align: center; } table { width:500px; } </style> <script src="https://cdn.bootcss.com/vue/2.4.4/vue.min.js"></script> </head> <body> <div class="app"> <table> <thead> <tr> <th style="line-height: 38px">选中数 {{checkedCount}}<input type="checkbox" v-model="allchecked" style="zoom:200%;vertical-align: middle"> </th> <th>name</th> <th>age</th> </tr> </thead> <tbody> <tr v-for="item in list"> <td><input type="checkbox" v-model="item.checked" style="zoom:200%"></td> <td>{{item.name}}</td> <td>{{item.age}}</td> </tr> </tbody> </table> </div> <script> var list=[ { name:'小明', age: 23, checked: false }, { name:'小红', age: 2, checked: true }, { name:'小蓝', age: 23, checked: true }, { name:'小bai', age: 40, checked: true }, { name:'王小二', age: 18, checked: false } ] new Vue({ el: '.app', data: { list }, computed: { allchecked: { // getter get: function () { return this.list.length == this.checkedCount }, // setter set: function (val) { //val就是点击之后,全选按钮的v-model值(状态),勾上后就是val的值就是true。未勾上就是false console.log(val) this.list.forEach(item => { item.checked = val }) } }, checkedCount: { // getter get: function () { var i = 0 this.list.forEach(item => { if (item.checked === true) i++ }) return i } } } }) </script> </body> </html>
使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码,可得如下运行效果:
希望本文所述对大家vue.js程序设计有所帮助。