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)
相关推荐
知识分享小能手2 小时前
Vue3 学习教程,从入门到精通,Axios 在 Vue 3 中的使用指南(37)
前端·javascript·vue.js·学习·typescript·vue·vue3
程序员码歌5 小时前
【零代码AI编程实战】AI灯塔导航-总结篇
android·前端·后端
用户21411832636026 小时前
免费玩转 AI 编程!Claude Code Router + Qwen3-Code 实战教程
前端
小小愿望7 小时前
前端无法获取响应头(如 Content-Disposition)的原因与解决方案
前端·后端
小小愿望7 小时前
项目启功需要添加SKIP_PREFLIGHT_CHECK=true该怎么办?
前端
烛阴7 小时前
精简之道:TypeScript 参数属性 (Parameter Properties) 详解
前端·javascript·typescript
海上彼尚8 小时前
使用 npm-run-all2 简化你的 npm 脚本工作流
前端·npm·node.js
开发者小天8 小时前
为什么 /deep/ 现在不推荐使用?
前端·javascript·node.js
如白驹过隙9 小时前
cloudflare缓存配置
前端·缓存
excel9 小时前
JavaScript 异步编程全解析:Promise、Async/Await 与进阶技巧
前端