el-select如何自定义下拉选项框的宽度

背景

默认情况下,el-select的下拉选项框的宽度会依据选项内容的长度而改变,当选项内容的长度过长的时候,下拉选项框的宽度也会变得很长,甚至可能会超出屏幕宽度,如下图所示:
在这里插入图片描述

解决办法

为了解决这一问题,我们可以通过给el-select添加focus事件的监听,当focus之后,动态改变el-option的宽度

<template>
  <div>
	<el-select v-model="textCaseType" placeholder="请选择语料素材类型" class="text-case-type-select" @focus="setOptionWidth">
       <el-option
         v-for="item in textCaseTypeOptions"
         :key="item.value"
         :label="item.label"
         :value="item.value">
        </el-option>
     </el-select>
  </div>
</template>

<script>
export default {
  name: 'CustomizeCreateVideo',
  components: {
  },
  props: {
  },
  data() {
    return {
      textCase: null,
      textCaseOptions: [{
        voice: 'aixia',
        label: 'aaaaaaaaaaaaaaaaaaaaaaaaasssssssssssssssssssssssssssssssssssssssqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqffffffffffffffffffffff',
        speechRate: -146,
        pitchRate: -7,
        volume: 80,
      }, {
        voice: 'xiaoxian',
        label: 'aaaaaaaaaaaaaaaaaaaaaaaaasssssssssssssssssssssssssssssssssssssssqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqffffffffffffffffffffff',
        speechRate: -135,
        pitchRate: 5,
        volume: 70,
      }, {
        voice: 'maoxiaomei',
        label: 'a啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊',
        speechRate: -125,
        pitchRate: 5,
        volume: 80,
      }, {
        voice: 'stanley',
        label: 'Stanley-沉稳男声',
        speechRate: -80,
        pitchRate: 10,
        volume: 80,
      }, {
        voice: 'ailun',
        label: '艾伦-悬疑解说',
        speechRate: -100,
        pitchRate: 3,
        volume: 80,
      }],
      selectOptionWidth: null,
    };
  },
  created() {
  },
  methods: {
    // 下拉框弹出时,设置弹框的宽度
    setOptionWidth(event){
      this.$nextTick(() => {
        this.selectOptionWidth = event.srcElement.offsetWidth + "px";
      }); 
    }
  },
};
</script>

在这里插入图片描述

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐