ElementUI el-select 组件动态设置disabled后,高度变更的问题解决办法

问题描述

Vue2 项目在使用 el-select 组件时,动态将disabled变更为了 true,元素的高度发生了变化。
在这里插入图片描述

问题原因

通过浏览器开发人员工具面板,发现,组件内的 input 元素被动态设置了height的样式:
在这里插入图片描述

在项目中检查后并没有找到触发这个设置的代码,所以怀疑是组件自身的逻辑。

于是找到 ElSelect 的源码(node_modules\element-ui\packages\select\src\select.vue),果然发现有一个方法里进行了 height 的设置:

resetInputHeight() {
  if (this.collapseTags && !this.filterable) return;
  this.$nextTick(() => {
    if (!this.$refs.reference) return;
    let inputChildNodes = this.$refs.reference.$el.childNodes;
    let input = [].filter.call(inputChildNodes, item => item.tagName === 'INPUT')[0];
    const tags = this.$refs.tags;
    const tagsHeight = tags ? Math.round(tags.getBoundingClientRect().height) : 0;
    const sizeInMap = this.initialInputHeight || 40;
    // 这里
    input.style.height = this.selected.length === 0
      ? sizeInMap + 'px'
      : Math.max(
        tags ? (tagsHeight + (tagsHeight > sizeInMap ? 6 : 0)) : 0,
        sizeInMap
      ) + 'px';
    if (this.visible && this.emptyText !== false) {
      this.broadcast('ElSelectDropdown', 'updatePopper');
    }
  });
},

这个方法在 disabled 变更时会触发:

watch: {
  selectDisabled() {
    this.$nextTick(() => {
      this.resetInputHeight();
    });
  },
...

我的解决办法

这个逻辑可能是为了多选时文本框的高度而设的,因为确认我的项目在单选时不需要考虑高度的变化,所以我直接替换这个监听回调,以解决了我的问题。

import Vue from 'vue'
import ElementUI from 'element-ui'

const elSelectWatcherSelectDisabled = ElementUI.Select.watch.selectDisabled
ElementUI.Select.watch.selectDisabled = function () {
  if (this.multiple) {
    elSelectWatcherSelectDisabled()
  }
}

Vue.use(ElementUI)

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-16 04:58:05       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-16 04:58:05       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-16 04:58:05       57 阅读
  4. Python语言-面向对象

    2024-07-16 04:58:05       68 阅读

热门阅读

  1. Go中的defer看似很简单,实则一点都不难

    2024-07-16 04:58:05       22 阅读
  2. 训练营第十三天 | 二叉树的递归遍历、层序遍历

    2024-07-16 04:58:05       23 阅读
  3. MySQL-字符集(charset)和校对规则(collation)

    2024-07-16 04:58:05       26 阅读
  4. 掌握Eureka:打造高效服务配置中心集成

    2024-07-16 04:58:05       27 阅读
  5. Docker的基本认识和常见命令以及场景介绍

    2024-07-16 04:58:05       21 阅读
  6. Spark和Hadoop作业之间的区别

    2024-07-16 04:58:05       28 阅读
  7. 七大排序算法的Python实现

    2024-07-16 04:58:05       21 阅读
  8. Linux命令更新-sort 和 uniq 命令

    2024-07-16 04:58:05       28 阅读