效果
动态修改:效果
代码
固定高度版本
注意点:
popper-class 尽量独一无二,防止影响其他页面样式
popper-append-to-body 的使用 及全局样式 & 样式穿透问题
<template>
<div>
<!-- :popper-append-to-body="false" -->
<el-select v-model="value" popper-class="custom-select-popper">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</div>
</template>
<script>
export default {
data() {
return {
options: [{
value: '选项1',
label: '黄金糕'
}, {
value: '选项2',
label: '双皮奶'
}, {
value: '选项3',
label: '蚵仔煎'
}, {
value: '选项4',
label: '龙须面'
}, {
value: '选项5',
label: '北京烤鸭'
}],
value: ''
}
}
}
</script>
// 二选其一:
// 如果el-select添加了 popper-append-to-body="false"
// 并且style标签添加了 scoped,需要使用 ::v-deep 选择器
<style lang="scss" scoped>
::v-deep .custom-select-popper {
height: 150px; // max-height 不生效
.el-scrollbar {
height: 100%;
.el-select-dropdown__wrap {
overflow-x: hidden; // 此处是隐藏底部自定义横向滚动条
}
}
}
</style>
// 未添加 popper-append-to-body="false" 时,popper是插入在body子级
// 需要去掉 scoped,但是无比务必使用独一无二的class,防止影响其他样式
<style lang="scss">
.custom-select-popper {
height: 150px;
.el-scrollbar {
height: 100%;
.el-select-dropdown__wrap {
overflow-x: hidden;
}
}
}
</style>
底部横向滚动条(样式按需修改):
动态修改高度版本(2024-12-25 更新: 支持动态修改下拉框高度)
<template>
<div>
<!-- :popper-append-to-body="false" -->
<!-- 当popper插入在select元素下时,--popper-height 需要在 el-select 标签 -->
<el-select
v-model="value"
popper-class="custom-select-popper"
:style="{'--popper-height': height}"
>
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
<el-button type="primary" @click="addOption">add option</el-button>
</div>
</template>
<script>
export default {
data() {
return {
options: [{
value: '选项1',
label: '黄金糕'
}, {
value: '选项2',
label: '双皮奶'
}],
value: ''
}
},
// 动态修改下拉框高度
computed: {
height() {
// 这里:34 是el-option的高度,+17 是popper标签有margin
const maxHeight = this.options.length * 34 + 17
return `${maxHeight > 150 ? 150 : maxHeight}px`
}
},
// popper 插入在 body 时使用
// 动态修改 body css变量
watch: {
height: {
immediate: true, // 初始化时进行一次高度计算
async handler(n) {
await this.$nextTick()
document.body.style.setProperty('--popper-height', n)
}
}
},
methods: {
addOption() {
const length = this.options.length
this.options.push({
value: '选项' + length + 1,
label: '选项' + length + 1
})
}
}
}
</script>
// 二选其一:
// 如果el-select添加了 popper-append-to-body="false"
// 并且style标签添加了 scoped,需要使用 ::v-deep 选择器
<style lang="scss" scoped>
::v-deep .custom-select-popper {
// height: 150px; // max-height 不生效
height: var(--popper-height);
.el-scrollbar {
height: 100%;
.el-select-dropdown__wrap {
overflow-x: hidden; // 此处是隐藏底部自定义横向滚动条
}
}
}
</style>
// 未添加 popper-append-to-body="false" 时,popper是插入在body子级
// 需要去掉 scoped,但是无比务必使用独一无二的class,防止影响其他样式
<style lang="scss">
.custom-select-popper {
// height: 150px; // 固定高度: 适用于option选项固定选项
height: var(--popper-height); // 动态高度:适用于option不固定时
.el-scrollbar {
height: 100%;
.el-select-dropdown__wrap {
overflow-x: hidden;
}
}
}
</style>