问题
使用element-ui的Select 选择器时,发现当下拉选项内容过长会导致下拉框超出input框的宽度,影响美观;如图:
需求
期望Select选择器下拉框能根据select的宽度自适应。
解决方案(暂时考虑到三种解决方案)
方案一(focus事件)
给el-select添加一个 input 获取焦点事件,获取当前select的input框的宽度,然后赋值给el-option元素
具体实现代码如下:
<el-form-item label="数据表名" prop="tableName">
<el-select
v-model="register.form.tableName"
placeholder="请选择数据表名"
clearable
filterable
style="width: 100%"
:disabled="register.title == register.updateTitle"
@change="tableNameChange"
@focus="setOptionWidth"
>
<-- @focus="setOptionWidth" : select input输入框获取焦点事件 -->
<el-option
v-for="(option, index) in this.unRegList"
:key="option.id+index"
:label="option.label"
:value="option.id"
:title="option.label"
:style="{width: selectOptionWidth }"
/>
</el-select>
</el-form-item>
setOptionWidth函数
// 设置select组件下拉框宽度
setOptionWidth(event) {
this.$nextTick(() => {
this.selectOptionWidth = event.srcElement.offsetWidth + "px";
});
},
这个方法唯一不好的就是,每使用一次select选择器就得写一个函数,定义一个变量,不是全局生效,比较繁琐。
方案二(popper-append-to-body属性)
设置popper-append-to-body = false; 不将弹出框插入至 body 元素中,而是插入到与el-input同层级,如图所示:
vue: 给el-select元素添加:popper-append-to-body="false"属性即可
<el-select
v-model="register.form.tableName"
placeholder="请选择数据表名"
clearable
filterable
style="width: 100%"
:disabled="register.title == register.updateTitle"
@change="tableNameChange"
:popper-append-to-body="false"
>
<el-option
v-for="(option, index) in this.unRegList"
:key="option.id+index"
:label="option.label"
:value="option.id"
:title="option.label"
/>
</el-select>
css: 样式需要写到公共样式表
// select下拉框宽度修改(与select input宽度一致,需设置select的:popper-append-to-body="false"属性)
.el-select.el-select--mini {
.el-select-dropdown.el-popper {
position: absolute !important;
top: 28px !important;
left: 0px !important;
width: inherit !important;
}
}
使用方案二需要实现这个效果只要给el-select添加:popper-append-to-body="false"即可,比方案一方便多了。
方案三(修改element-ui源码)
element-ui仓库拉取element-ui项目,在packages找到select
通过查看源码发现下拉框的minWidth值就是select输入框宽度,所以说只需要给class为el-select-dropdown el-popper的div元素添加width:minWidth属性即可;
修改好后需要执行 npm run dist 重新打包,然后把打包好的lib替换掉node_modules下的element-ui下的lib文件夹重新运行即可。