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>
相关推荐
刘 怼怼40 分钟前
【520 特辑】用 HTML/CSS/JavaScript 打造浪漫炫酷的表白网页
javascript·css·html
_龙小鱼_40 分钟前
Vue响应式系统演进与实现解析
前端·vue.js
哎呦你好1 小时前
CSS 选择器入门
开发语言·前端·css·html
云隙阳光i1 小时前
Vue3 中使用 provide/inject 实现跨层级组件传值失败的原因及解决方案
前端·javascript·vue.js
资深前端之路1 小时前
vue+three.js 五彩烟花效果封装+加载字体
前端·javascript·vue.js
alicema11112 小时前
matlab+opencv车道线识别
前端·opencv·matlab
caihuayuan52 小时前
使用 Java 开发 Android 应用:Kotlin 与 Java 的混合编程
java·大数据·vue.js·spring boot·课程设计
火星牛2 小时前
SPA模式下的es6如何加快宿主页的显示速度
前端·ecmascript·es6
疏狂难除2 小时前
【Tauri2】046—— tauri_plugin_clipboard_manager(一)
前端·clipboard·tauri2
污斑兔3 小时前
VMWare清理后,残留服务删除方案详解
前端