让el-option和el-select宽度保持一致

有时候我们用elementUI时会发现,el-option宽度总是达不到100%,就算你给它设置了宽100%一样不生效。如下是最终的效果图:
请添加图片描述
原理:DOM挂载完毕后,获取 el-selcet宽度,并赋值给 el-option 。
如果 el-select 宽度不确定,可以在 focus 时获取 el-select 宽度,赋值给 el-option。
下面是Vue3写法:

<el-select
           v-model="columnContentList"
           placeholder="请输入关键词"
           ref="columnContentSelect"
           class="column-content-list">
    <el-option
               v-for="item in columnContentListOptions"
               :key="item.value"
               :label="item.label"
               :style="{'width': selectOptionWidth}"
               :value="item.value">
    </el-option>
</el-select>

// 设置选项框与输入框同宽度
const selectOptionWidth = ref('')
const columnContentSelect = ref(null)
onMounted(()=> {
    
    
    nextTick(() => {
    
    
        selectOptionWidth.value = columnContentSelect.value.$el.offsetWidth + "px";
    });
})

下面是Vue2写法:

  <div style="width:100%;">
        <el-select
          v-model.trim="formData.docTag"
          multiple
          filterable
          allow-create
          placeholder="请选择档案标签"
          ref="columnContentSelect"
        >
          <el-option
            v-for="item in doctagList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :style="{ width: selectOptionWidth }"
          >
            <div style="float: left;display: flex;">
              <div
                style="width:0.625rem;height:0.625rem;border-radius:0.3125rem;margin-top:.75rem;margin-right:0.5rem"
                :style="{ background: item.color ? item.color : '#1b9aee' }"
              ></div>
              <div>
                {
    
    {
    
     item.label }}
              </div>
            </div>

            <div style="float: right; color: #8492a6; font-size: 1rem">
              <i
                slot="reference"
                class="el-icon-edit"
                style="margin-right:1.5rem;"
                @click.stop.prevent="editTag(item)"
              ></i>

              <!-- <i class="el-icon-delete" @click.stop.prevent="deleteTag(item)"></i>  -->
            </div>
          </el-option>
        </el-select>
      </div>

<script>
export default{
    
     
     data(){
    
    
      return {
    
    
       selectOptionWidth: "100%"
      }
     },
     mounted() {
    
    
      this.$nextTick(() => {
    
    
        this.selectOptionWidth =
        this.$refs.columnContentSelect.$el.offsetWidth + "px";
    });
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/qq_37635012/article/details/129959761