在Vue-element-ui中
在element-ui中Select 选择器是不支持全选反选的,有些场景下,我们的下拉数据较多,我们不可能一个一个的选择,这是在我们的业务中常见的场景,所以我们把Element-ui中的Select选择器进行了一次简单的封装,让他支持全选反选.
<template>
<el-select
multiple
collapse-tags
v-model="selectedArray"
@change="changeSelect"
@remove-tag="removeTag"
placeholder="请选择"
>
<el-option label="全选" value="全选" @click.native="selectAll"></el-option>
<el-option
v-for="(item, index) in options"
:key="index"
:label="item.label"
:value="item.value"
></el-option>
</el-select>
</template>
<script>
export default {
props: {
dataArr: {
type: Array,
default() {
return [];
},
},
},
watch: {
dataArr(oldVal) {
this.options = oldVal === undefined ? [] : oldVal;
},
},
data() {
return {
selectedArray: [],
options: [],
};
},
methods: {
selectAll() {
if (this.selectedArray.length < this.options.length) {
this.selectedArray = [];
this.options.map((item) => {
this.selectedArray.push(item.value);
});
this.selectedArray.unshift("全选");
} else {
this.selectedArray = [];
}
this.$emit("SelectedData", this.selectedArray);
},
changeSelect(val) {
if (!val.includes("全选") && val.length === this.options.length) {
this.selectedArray.unshift("全选");
} else if (val.includes("全选") && val.length - 1 < this.options.length) {
this.selectedArray = this.selectedArray.filter((item) => {
return item !== "全选";
});
}
this.$emit("SelectedData", this.selectedArray);
},
removeTag(val) {
if (val === "全选") {
this.selectedArray = [];
}
this.$emit("SelectedData", this.selectedArray);
},
},
};
</script>
参数 | 说明 | 类型 |
dataArr | 接受下拉选择框的数据 | Array |
SelectedData(Event) | 选中的Value | Array |