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>
相关推荐
葡萄城技术团队几秒前
解锁 SpreadJS 扩展能力:ECharts 集成与自定义渲染实战
前端
来一颗砂糖橘2 分钟前
CSS 清除浮动深度解析:从 clear: both 到现代布局方案
前端·css·clearboth·清除浮动
南宫码农4 分钟前
Node.js和npm本地安装详细教程(全系统适配)
前端·npm·node.js
我命由我123459 分钟前
前端开发 - this 指向问题(直接调用函数、对象方法、类方法)
开发语言·前端·javascript·vue.js·react.js·html5·js
小黑的铁粉10 分钟前
ecahrts图形多的页面,怎么解决数据量大的渲染问题?
前端·echarts
低保和光头哪个先来11 分钟前
TinyEditor 篇1:实现工具栏按钮向服务器上传图片
服务器·开发语言·前端·javascript·vue.js·前端框架
还是大剑师兰特14 分钟前
vue3+vite+JS,使用Echarts封装一个饼图,父子组件联动
javascript·vue.js·echarts
A黄俊辉A19 分钟前
webstorm+vue+esLint+pretter配置
前端·vue.js·webstorm
TYFHVB1220 分钟前
2026六大主流CRM横评,五大核心维度深度解析
大数据·前端·数据结构·人工智能
LiuMingXin23 分钟前
断网也能装包? 我在物理隔离内网搭了一套完整的私有npm仓库
前端·面试·npm