记录element2.x二次封装下拉选择器问题
-
UI库: element-ui
-
版本号: 2.15.11
-
基础组件: el-select
-
需解决的问题:
- 下拉选项不被遮挡(使用 :popper-append-to-body=“true”)
- 解决文本内容需按需求展示
- 支持单选多选
-
以下是实现过程中遇到的问题
- 下拉出现闪动情况(单选模式)
- 将 automatic-dropdown设置为true
- 点击输入框文本内容下拉选项出现闪动 (需求需要展示文本按照下图展示, 多选模式)
- 实现思路: 使用一个div将内容按照需求展示,后置于el-select的input上方
- 引发问题: 选择后点击文本内容,下拉选项不出来
- 解决方案:
- 使用时间戳的形式生成独一的class样式
eshop-select-${domId}
- 在点击文本框时触发
openSelect
方法(可见里面具体代码)
- 使用时间戳的形式生成独一的class样式
完整代码(不含css)
<template>
<div :style="{ width: width + 'px' }" class="eshop-select-component-container">
<el-select
ref="selectRef"
:automatic-dropdown="isMultiple && showText ? true : false"
:popper-class="`eshop-select-component ${isMultiple ? 'pr-40' : ''} eshop-select-${domId}`"
:class="{ 'not-show-tags': !isShowTag }"
:multiple="isMultiple"
v-model="selectValue"
:placeholder="placeholder"
:collapse-tags="true"
@change="handlerChange"
@blur="handlerBlur"
>
<el-option v-for="item in selectList" :key="item.id" :label="item.title" :value="item.id"></el-option>
</el-select>
<!-- 以长文案展示所选内容 -->
<el-tooltip effect="dark" v-if="!isShowTag && showText" :content="showText" placement="top">
<p @click="openSelect" class="select-text-class">{{ showText }}</p>
</el-tooltip>
</div>
</template>
<script>
export default {
name: 'DiySelectComponent',
props: {
// 提示文案
placeholder: {
type: String,
default: '请选择',
},
// 选项数组
selectList: {
type: Array,
required: true,
},
// 选中值
selectId: {
type: [Array, Number, String],
required: true,
},
// 是否支持多选
isMultiple: {
type: Boolean,
default: false,
},
// 是否值改变就出发更改
isChange: {
type: Boolean,
default: false,
},
// 是否以tag展示
isShowTag: {
type: Boolean,
default: false,
},
// 宽度
width: {
type: Number,
default: 120,
},
},
computed: {
showText() {
if (Array.isArray(this.selectValue) && this.selectValue.length) {
const name = []
this.selectValue.forEach(item => {
const show = this.selectList.find(obj => String(obj.id) === String(item))
show?.title && name.push(show.title)
})
return name.join(',') || this.placeholder
}
return ''
},
},
data() {
return {
selectValue: this.selectId,
domId: new Date().getTime()
}
},
methods: {
// 值改变触发
handlerChange(val) {
this.selectValue = val
this.isChange && this.$emit('callBackF', val)
},
// 失去焦点
handlerBlur() {
this.$emit('callBackF', this.selectValue || [])
},
// 打开内容
openSelect() {
const dom = document.querySelector(`.eshop-select-${this.domId}`)
const flag = dom.style.display === 'none'
flag && this.$refs.selectRef.focus()
},
},
}
</script>