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)
相关推荐
问心无愧05134 小时前
ctf show web入门160 161
前端·笔记
李小白664 小时前
第四天-WEB服务器基本原理,IIS服务
运维·服务器·前端
humcomm5 小时前
AI编程时代新前端职位
前端·ai编程
好家伙VCC5 小时前
Web Components主题热切换方案揭秘
java·前端
甲维斯5 小时前
Kimi版超级玛丽效果“惊人”,配额不足5厘米!
前端·人工智能
hboot5 小时前
AI工程师第一课 - Python
前端·后端·python
凉菜凉凉6 小时前
AI时代,被抛弃的前端
前端·ai
console.log('npc')6 小时前
AI前端工程与生成式UI学习路线
前端·人工智能·ui
huangdong_6 小时前
淘宝商品SKU图自动分类技术深度解析:从DOM解析到智能归档
开发语言·javascript·ecmascript
梦曦i6 小时前
uni-router v1.1.1发布:守卫超时保护+路由监听
前端·uni-app