elementUI+JS实现全选与反选

在实际项目开发过程中,遇到的需求,需要实现全选以及取消全选等功能,主要使用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 = val70  }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.chooseFruit80  }81  }82  })83 </script>84 </body>85 </html>

相关文章