elementUI+JS实现全选与反选

时间:2023-03-09 04:55:34
elementUI+JS实现全选与反选

在实际项目开发过程中,遇到的需求,需要实现全选以及取消全选等功能,主要使用ElementUI + JS来实现,具体代码如下:

 <!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>elementUI+JS实现全选与反选</title>
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
<span>请选项喜欢的水果:</span>
<el-select
v-model="chooseFruit"
multiple
collapse-tags
placeholder="请选择"
style="width: 75%;border-radius: 20px;margin-top:60px;width:280px;"
@change='selectAll'>
<el-option
v-for="item in fruitLists"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
var vm = new Vue({
el:'#app',
data:{
fruitLists: [
{ value: 'all', label: 'ALL' },
{ value: 'apple6', label: 'app1e' },
{ value: 'orange6', label: 'orange' },
{ value: 'pear6', label: 'pear' },
{ value: 'banana6', label: 'banana' },
{ value: 'mongo6', label: 'mongo' }
],
oldFruit: [],
chooseFruit: []
},
methods:{
selectAll(val) {
var allFruit = []; //定义包含所有水果的空数组
this.fruitLists.forEach((item,index) => { //给数组赋值
allFruit.push(item.value);
})
// 定义存储上一次选中的水果,以作下一次对比
var lastFruitVal = this.oldFruit.length === 1 ? this.oldFruit[0] : [];
// 全选
if (val.includes('all')){
this.chooseFruit = allFruit;
}
// 取消全选
if (lastFruitVal.includes('all') && !val.includes('all')){
this.chooseFruit = [];
}
// 点击非全部选中,需要排除全部选中以及当前点击的选项
// 新老数据都有全部选中的情况
if (lastFruitVal.includes('all') && val.includes('all')) {
var index = val.indexOf('all')
val.splice(index, 1) // 排除全选选项
this.chooseFruit = val
}
// 全选未选,但是其他选项全部选上时,则全选选上,上次和当前都没有全选
if (!lastFruitVal.includes('all') && !val.includes('all')) {
console.log(11)
if (val.length === allFruit.length - 1){
this.chooseFruit = ['all'].concat(val)
}
}
// 储存当前最后的结果,作为下次的老数据进行对比
this.oldFruit[0] = this.chooseFruit
}
}
})
</script>
</body>
</html>