在實際項目開發過程中,遇到的需求,需要實現全選以及取消全選等功能,主要使用ElementUI + JS來實現,具體代碼如下:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>elementUI+JS實現全選與反選</title> 8 <!-- 引入樣式 --> 9 <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> 10 </head> 11 <body> 12 <div id="app"> 13 <span>請選項喜歡的水果:</span> 14 <el-select 15 v-model="chooseFruit" 16 multiple 17 collapse-tags 18 placeholder="請選擇" 19 style="width: 75%;border-radius: 20px;margin-top:60px;width:280px;" 20 @change='selectAll'> 21 <el-option 22 v-for="item in fruitLists" 23 :key="item.value" 24 :label="item.label" 25 :value="item.value"> 26 </el-option> 27 </el-select> 28 </div> 29 30 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> 31 <!-- 引入組件庫 --> 32 <script src="https://unpkg.com/element-ui/lib/index.js"></script> 33 <script> 34 var vm = new Vue({ 35 el:'#app', 36 data:{ 37 fruitLists: [ 38 { value: 'all', label: 'ALL' }, 39 { value: 'apple6', label: 'app1e' }, 40 { value: 'orange6', label: 'orange' }, 41 { value: 'pear6', label: 'pear' }, 42 { value: 'banana6', label: 'banana' }, 43 { value: 'mongo6', label: 'mongo' } 44 ], 45 oldFruit: [], 46 chooseFruit: [] 47 }, 48 methods:{ 49 selectAll(val) { 50 var allFruit = []; //定義包含所有水果的空數組 51 this.fruitLists.forEach((item,index) => { //給數組賦值 52 allFruit.push(item.value); 53 }) 54 // 定義存儲上一次選中的水果,以作下一次對比 55 var lastFruitVal = this.oldFruit.length === 1 ? this.oldFruit[0] : []; 56 // 全選 57 if (val.includes('all')){ 58 this.chooseFruit = allFruit; 59 } 60 // 取消全選 61 if (lastFruitVal.includes('all') && !val.includes('all')){ 62 this.chooseFruit = []; 63 } 64 // 點擊非全部選中,需要排除全部選中以及當前點擊的選項 65 // 新老數據都有全部選中的情況 66 if (lastFruitVal.includes('all') && val.includes('all')) { 67 var index = val.indexOf('all') 68 val.splice(index, 1) // 排除全選選項 69 this.chooseFruit = val 70 } 71 // 全選未選,但是其他選項全部選上時,則全選選上,上次和當前都沒有全選 72 if (!lastFruitVal.includes('all') && !val.includes('all')) { 73 console.log(11) 74 if (val.length === allFruit.length - 1){ 75 this.chooseFruit = ['all'].concat(val) 76 } 77 } 78 // 儲存當前最后的結果,作為下次的老數據進行對比 79 this.oldFruit[0] = this.chooseFruit 80 } 81 } 82 }) 83 </script> 84 </body> 85 </html>