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

问题描述

Vue2 项目在使用 el-select 组件时,动态将disabled变更为了 true,元素的高度发生了变化。

问题原因

通过浏览器开发人员工具面板,发现,组件内的 input 元素被动态设置了height的样式:

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

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

js 复制代码
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 变更时会触发:

js 复制代码
watch: {
  selectDisabled() {
    this.$nextTick(() => {
      this.resetInputHeight();
    });
  },
...

我的解决办法

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

js 复制代码
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)
相关推荐
恋猫de小郭3 分钟前
为什么跨平台框架可以适配鸿蒙,它们的技术原理是什么?
android·前端·flutter
云浪6 分钟前
元素变形记:CSS 缩放函数全指南
前端·css
明似水21 分钟前
用 Melos 解决 Flutter Monorepo 的依赖冲突:一个真实案例
前端·javascript·flutter
独立开阀者_FwtCoder31 分钟前
stagewise:让AI与代码编辑器无缝连接
前端·javascript·github
清沫33 分钟前
Cursor Rules 开发实践指南
前端·ai编程·cursor
江城开朗的豌豆39 分钟前
JavaScript篇:对象派 vs 过程派:编程江湖的两种武功心法
前端·javascript·面试
不吃糖葫芦340 分钟前
App使用webview套壳引入h5(二)—— app内访问h5,顶部被手机顶部菜单遮挡问题,保留顶部安全距离
前端·webview
菥菥爱嘻嘻1 小时前
JS手写代码篇---手写ajax
开发语言·javascript·ajax
江城开朗的豌豆1 小时前
JavaScript篇:字母侦探:如何快速统计字符串里谁才是'主角'?
前端·javascript·面试
kite01217 小时前
浏览器工作原理06 [#]渲染流程(下):HTML、CSS和JavaScript是如何变成页面的
javascript·css·html