element虽然功能很强大,也很方便,但是在实际开发中还是有很多不足,比方说下拉框多选时没有全选功能,这里的下拉框包含el-select和el-cascader级联选择器。这里我们都来封装一个组件,弥补下这个不足。
这里组件我们采用的是vue2.0,来看下代码实现:
<template>
<el-select
v-model="currentChoiceEle"
:size="size"
:style="{width: width + 'px'}"
:filterable="filterable"
multiple
collapse-tags
collapse-tags-tooltip
@change="selectChange"
>
<el-option :label="allOptions.label" :value="allOptions.value"></el-option>
<el-option v-for="(item, i) in options" :key="i" :label="item.label" :value="item.value"> </el-option>
</el-select>
</template>
<script>
/**
* options {label: "", value: ""}
* width 宽度
* 获取选中结果 change事件
* all 是全部
* size 大小
* filterable 是否支持筛选
*/
export default {
name: "AiSelectAllEle",
props: {
options: {
type: Array,
default: () => {
return [];
}
},
width: {
type: Number,
default: 180
},
filterable: {
type: Boolean,
default: true
},
size: {
type: String,
default: "mini"
}
},
watch: {
options() {
if (!this.options.length) {
this.currentChoiceEle = [];
return;
}
this.currentChoiceEle = [];
this.selectStoreAll();
this.sendSelectObj();
}
},
beforeDestroy() {
this.currentChoiceEle = [];
},
data() {
return {
allOptions: { label: "全部", value: "all" }, // 全部
saveSelectData: [],
currentChoiceEle: []
};
},
mounted() {
if (!this.options.length) return;
this.selectStoreAll();
this.sendSelectObj();
},
methods: {
selectChange(val) {
let all = this.allOptions.value;
// 之前没有全选 现在有了 点击了全选 全部选中
if (val && !this.saveSelectData.includes(all) && val.includes(all)) {
let selectArray = [];
this.options.forEach((item) => {
selectArray.push(item.value);
});
selectArray.unshift(this.allOptions.value);
val = [...selectArray];
this.currentChoiceEle = selectArray;
this.saveSelectData = [...val];
this.$nextTick(() => {
this.sendSelectObj();
});
return;
}
// 之前有全选 又点击了全选 全取消
if (val && this.saveSelectData.includes(all) && !val.includes(all)) {
this.currentChoiceEle = [];
this.saveSelectData = [];
this.$nextTick(() => {
this.sendSelectObj();
});
return;
}
// 当点选了除全部按钮外的所有 选中全部按钮
if (val && !val.includes(all) && val.length === this.options.length) {
val.unshift(all);
}
// 当全部选项都选中 这时取消了除全部按钮外的一个 去掉选中全部按钮
if (val && val.includes(all) && val.length - 1 < this.options.length) {
val = val.filter((item) => {
return item !== this.allOptions.value;
});
this.currentChoiceEle = [...val];
}
this.sendSelectObj();
this.saveSelectData = [...val];
},
selectStoreAll() {
if (this.currentChoiceEle.length < this.options.length) {
let selectArray = [];
this.options.forEach((item) => {
selectArray.push(item.value);
});
selectArray.unshift(this.allOptions.value);
this.currentChoiceEle = selectArray;
} else {
this.currentChoiceEle = [];
}
this.saveSelectData = [...this.currentChoiceEle];
},
sendSelectObj() {
this.$emit("change", this.currentChoiceEle);
}
}
};
</script>
<style scoped></style>
这个代码干货满满,大家直接复制到项目中即可,使用时:
<ai-select-all-ele
:options="optionsList"
@change="selectChangeFun"
:width="150"
/>
optionsList = [
{
label: "商品1",
value: 1,
},
{
label: "商品2",
value: 2,
},
]
代码逻辑都有注释,有帮助到大家的话,点个赞不过分吧!