【el-tooltips改造】Vue实现文本溢出才显示el-tooltip,否则不显示el-tooltips

实现原理:

使用disabled属性控制el-tooltip的content显示与隐藏;

目标:

1行省略、多行省略、可缩放页面内的文本省略都有效。

实现方式:

1、自定义全局指令,tooltipAutoShow.js代码如下(参考的el-table中的内容超出才显示tooltips的逻辑):

javascript 复制代码
/**
* tooltip-auto-show tooltip不超长则不显示
*/
import Vue from 'vue'
import { getStyle } from 'element-ui/src/utils/dom'
export default {
  inserted(el, binding, vnode) {
    el.__vueOverflowTooltipMouseenter__ = function(e) {
      const defalutSilent = !!Vue.config.silent
      Vue.config.silent = true
      vnode.componentInstance.disabled = true
      const range = document.createRange()
      range.setStart(el, 0)
      range.setEnd(el, el.childNodes.length)
      const rangeWidth = Math.round(range.getBoundingClientRect().width)
      const padding = (parseInt(getStyle(el, 'paddingLeft'), 10) || 0) + (parseInt(getStyle(el, 'paddingRight'), 10) || 0)
      let elWidth = el.offsetWidth
      // 兼容getBoundingClientRect().width值受scale缩放影响
      if (el.offsetWidth < Math.round(el.getBoundingClientRect().width)) {
        elWidth = Math.round(el.getBoundingClientRect().width)
      }
      // 1行省略
      if (rangeWidth + padding > elWidth || el.scrollWidth > elWidth) {
        vnode.componentInstance.disabled = false
      }
      // 处理多行省略
      if (getStyle(el, '-webkit-line-clamp') > 1 && el.scrollHeight > el.offsetHeight) {
        vnode.componentInstance.disabled = false
      }
      Vue.config.silent = defalutSilent
    }
    el.addEventListener('mouseenter', el.__vueOverflowTooltipMouseenter__)
  },
  unbind: function(el) {
    el.removeEventListener('mouseenter', el.__vueOverflowTooltipMouseenter__)
    delete el.__vueOverflowTooltipMouseenter__
  }
}
javascript 复制代码
import tooltipAutoShow from './module/tooltipAutoShow'

Vue.directive('tooltip-auto-show', tooltipAutoShow)

2、使用方式:

html 复制代码
<el-tooltip v-tooltip-auto-show class="" effect="dark" :content="data.name" placement="top-start">
    <div>{{ data.name }}</div>
</el-tooltip>

3、实现效果:

相关推荐
佛系打工仔3 小时前
绘制K线第二章:背景网格绘制
android·前端·架构
计算机毕设VX:Fegn08954 小时前
计算机毕业设计|基于springboot + vue医院设备管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
明天好,会的4 小时前
分形生成实验(五):人机协同破局--30万token揭示Actix-web状态管理的微妙边界
运维·服务器·前端
C_心欲无痕5 小时前
nginx - alias 和 root 的区别详解
运维·前端·nginx
北辰alk5 小时前
Vue 路由信息获取全攻略:8 种方法深度解析
vue.js
北辰alk5 小时前
Vue 三剑客:组件、插件、插槽的深度辨析
vue.js
北辰alk5 小时前
Vue Watch 立即执行:5 种初始化调用方案全解析
vue.js
北辰alk5 小时前
Vue 组件模板的 7 种定义方式:从基础到高级的完整指南
vue.js
北辰alk5 小时前
深入理解 Vue 生命周期:created 与 mounted 的核心差异与实战指南
vue.js