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)
相关推荐
小二·6 分钟前
Python Web 开发进阶实战:Flask 项目中的表单验证、错误处理与用户体验优化
前端·python·flask
天荒地老笑话么7 分钟前
IntelliJ IDEA 运行 Tomcat 报错:Please, configure Web Facet first!
java·前端·tomcat·intellij-idea
王五周八7 分钟前
html转化为base64编码的pdf文件
前端·pdf·html
神色自若10 分钟前
vue3 带tabs的后台管理系统,切换tab标签后,共用界面带参数缓存界面状态
前端·vue3
мо仙堡杠把子ご灬10 分钟前
微前端架构实践:避免Vuex模块重复注册的崩溃陷阱
前端
叫我:松哥15 分钟前
基于机器学习的地震风险评估与可视化系统,采用Flask后端与Bootstrap前端,系统集成DBSCAN空间聚类算法与随机森林算法
前端·算法·机器学习·flask·bootstrap·echarts·聚类
赵民勇15 分钟前
JavaScript中的Mixin模式详解
javascript·ecmascript
呆头鸭L19 分钟前
用vue3+ts+elementPlus+vite搭建electron桌面端应用
前端·vue.js·electron
aPurpleBerry19 分钟前
React Hooks(数据驱动、副作用、状态传递、状态派生)
前端·react.js·前端框架
IT_陈寒20 分钟前
2025年React生态最新趋势:我从Redux迁移到Zustand后性能提升40%的心得
前端·人工智能·后端