vue基礎之全選,不選
阿新 • • 發佈:2019-01-02
先上效果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.bootcss.com/vue/2.5.17-beta.0/vue.min.js"></script> </head> <body> <style type="text/css"> body{margin: 0;} .main{ width: 600px; margin-top: 10px; margin-left:auto; margin-right:auto; } th{ white-space: nowrap } .table{width: 100%;background-color: transparent;border-collapse:collapse;border-spacing:0} .table th,.table td{padding:8px;line-height:20px;text-align: center;} .table-border{border-top:1px solid #ddd;} .table-border th,.table-border td{border-bottom: 1px solid #ddd;} .table-bg thead{background-color: #f5fafe;} .table-bordered{border:1px solid #ddd;border-collapse:separate;*border-collapse:collapse;border-left:0} .table-bordered th,.table-bordered td{border-left:1px solid #ddd} .table-border.table-bordered{border-bottom:0} .table-hover tbody tr:hover td{background-color:#f5f5f5} </style><div class="main" id="app"> <table class="table table-border table-bordered table-bg table-hover"> <thead> <tr> <th width="25"><input type="checkbox" v-model="issongListAll">全選</th> <th width="75">歌單</th> <th width="120">歌手</th> <th width="80">專輯</th> </tr> </thead> <tbody> <tr v-for="item,index in songList"> <td><input type="checkbox" v-model="item.checked">{{item.id}}</td> <td>{{item.name}}</td> <td>{{item.song}}</td> <td>{{item.album}}</td> </tr> </tbody> </table> <div> 歌手有:{{songLen}}位 專輯有:{{albumSum}}張 </div> </div> <script> let data=[ { id:Date.now()+Math.random(), name:'王傑', song:'泡沫', checked:false, album:5 }, { id:Date.now()+Math.random(), name:'王傑2', song:'泡沫22', checked:false, album:10 }, { id:Date.now()+Math.random(), name:'王傑22', song:'泡沫22', checked:false, album:10 } ] new Vue({ el:'#app', data:{ songList:data }, computed:{
issongListAll:{ //every() 只要陣列中的每一個都滿足就true,某一項不滿足就false get(){ return this.songList.every(item=>{ return item.checked }) }, set(val){ this.songList.forEach(item=>item.checked=val) } }, songLen(){ return this.songList.filter(item=>item.checked).length }, albumSum(){ return this.songList.filter(item=>item.checked).reduce((n,j)=>{ return n+j.album },0) } } }) </script> </body> </html>