vue2中,下拉框多选和全选的实现
- 代码布局
- 在methods: 中添加功能函数
- 较为完整的一个整体代码:
如图所示点击全选即可完成下拉框中全部子项的全部的选中,同时取消全选即可全部取消选择。
代码布局
<div class="chos-box2"><span>屏蔽策略名称</span>:<el-selectv-model="cluster_nameArr"filterablesize="small"multipleplaceholder="多选(可全选)"collapse-tags="collapseTags"clearable@change="searchDataHA"><el-optionlabel="全选"value="全选"@click.native="selectAllHA"v-if="options4.length"></el-option><el-optionv-for="item in options4":key="item":label="item":value="item"></el-option></el-select></div>
相关的el参数可以查询,
在methods: 中添加功能函数
method:{searchDataHA(val) {if (!val.includes("全选") && val.length === this.options4.length) {this.cluster_nameArr.unshift("全选");} else if (val.includes("全选") &&val.length - 1 < this.options4.length) {this.cluster_nameArr = this.cluster_nameArr.filter((item) => {return item !== "全选";});}this.page = 1;this.getConfigData();//用来请求数据的函数},}
较为完整的一个整体代码:
<template>
<div class="chos-box2"><span>屏蔽策略名称</span>:<el-selectv-model="cluster_nameArr"filterablesize="small"multipleplaceholder="多选(可全选)"collapse-tags="collapseTags"clearable@change="searchDataHA"><el-optionlabel="全选"value="全选"@click.native="selectAllHA"v-if="options4.length"></el-option><el-optionv-for="item in options4":key="item":label="item":value="item"></el-option></el-select></div></template><script>export default {data() {// 已选中选项mulSelecteds: {type: Array,default() {return [];},},collapseTags: {type: Boolean,default: true,},}method:{searchDataHA(val) {if (!val.includes("全选") && val.length === this.options4.length) {this.cluster_nameArr.unshift("全选");} else if (val.includes("全选") &&val.length - 1 < this.options4.length) {this.cluster_nameArr = this.cluster_nameArr.filter((item) => {return item !== "全选";});}this.page = 1;this.getConfigData();//用来请求数据的函数},selectAllHA() {if (this.cluster_nameArr.length < this.options4.length) {this.cluster_nameArr = [];this.options4.map((item) => {this.cluster_nameArr.push(item);});this.cluster_nameArr.unshift("全选");} else {// 取消全选this.cluster_nameArr = [];}console.log("全选", this.checked, this.options2, this.selectedArr);},},watch: {//用来监听变量mulSelecteds: {handler(newVal, oldVal) {this.selectedArr = newVal;if (!this.selectedArr.includes("全选") &&this.selectedArr.length &&this.selectedArr.length === this.options2.length) {this.selectedArr.unshift("全选");}},immediate: true,},},}</script>
<style lang="scss" scoped>.chos-box2 {margin-right: 25px;span {display: inline-block;width: 115px;}}
</style>
}