el-tooltips设置文字超出省略才显示

定义一个全局的自定义指令,一般来说是在directive文件夹下新建文件,复制下面的代码

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 = range.getBoundingClientRect().width
      const padding = (parseInt(getStyle(el, 'paddingLeft'), 10) || 0) + (parseInt(getStyle(el, 'paddingRight'), 10) || 0)

      if (binding.value?.canChangeScale && el.offsetWidth < el.getBoundingClientRect().width) { // 可缩放页面:getBoundingClientRect().width值会受scale缩放影响
        const deviationValue = range.getBoundingClientRect().width - el.getBoundingClientRect().width
        if (deviationValue !== 0 && deviationValue > 0.1) { // 忽略0.1以下的偏差
          const elWidth = el.getBoundingClientRect().width
          // 1行省略
          if (rangeWidth + padding > elWidth || el.scrollWidth > elWidth) {
            vnode.componentInstance.disabled = false
          }
        }
      } else {
        const elWidth = el.offsetWidth
        // 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__
  }
}

在使用el-tooltips的文件中引入

javascript 复制代码
import tooltipAutoShow from './module/tooltipAutoShow'

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

并且这样使用

javascript 复制代码
<el-tooltip v-tooltip-auto-show class="" effect="dark" :content="data.name" placement="top-start">
    <div>{{ data.name }}</div>
</el-tooltip>
相关推荐
JoyGqz32 分钟前
Vue 2 EOL 之后还在跑生产?这个开源安全分支已修主流 CVE,一行依赖即可接入
vue.js
zz58834 分钟前
面试官问"JS的类型"时,到底想听到什么?
javascript
gjwjuejin36 分钟前
全埋点技术方案深度剖析:从事件代理到无痕采集的完整实现
javascript
十有八七43 分钟前
AI 开发,本质是一场文档的生命周期管理
前端·人工智能
Lkstar44 分钟前
Vue 3 Composition API 进阶:自定义 Hooks 与 provide/inject 的高级玩法
vue.js·面试
Hyyy1 小时前
普通前端自救记录——第0周
前端
前端若水2 小时前
在 Vue 2 与 Vue 3 中使用 markdown-it-vue 渲染 Markdown 和数学公式
前端·javascript·vue.js
之歆2 小时前
DAY_10 JavaScript 深度解析:原型链 · 引用类型 · 内置对象 · 数组方法全攻略(下)
开发语言·前端·javascript·ecmascript
Aolith2 小时前
用 Vue 递归组件实现嵌套回复,我的评论系统升级全记录
vue.js·全栈
行星飞行2 小时前
从 cursor 、 Claude code 迁移到 codex,30 分钟快速上手 codex 常用技巧
前端