文章目錄
- 效果
- 動態修改:效果
- 代碼
- 固定高度版本
- 動態修改高度版本(2024-12-25 更新: 支持動態修改下拉框高度)
效果
動態修改:效果
代碼
固定高度版本
注意點:
popper-class 盡量獨一無二,防止影響其他頁面樣式
popper-append-to-body 的使用 及全局樣式 & 樣式穿透問題
<template><div><!-- :popper-append-to-body="false" --><el-select v-model="value" popper-class="custom-select-popper"><el-optionv-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-selectv-model="value"popper-class="custom-select-popper":style="{'--popper-height': height}"><el-optionv-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標簽有marginconst maxHeight = this.options.length * 34 + 17return `${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.lengththis.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>