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>
相关推荐
Lear4 小时前
UniApp PDF文件下载与预览功能完整实现指南
前端
Heo4 小时前
关于XSS和CSRF,面试官更喜欢这样的回答!
前端·javascript·面试
7***A4434 小时前
Vue自然语言处理应用
前端·vue.js·自然语言处理
徐小夕5 小时前
耗时一周,我把可视化+零代码+AI融入到了CRM系统,使用体验超酷!
javascript·vue.js·github
高阳言编程5 小时前
vue2 + node + express + MySQL 5.7 的购物系统
前端
5***a9755 小时前
React Native性能优化技巧
javascript·react native·react.js
y***54885 小时前
React依赖
前端·react.js·前端框架
2***B4495 小时前
React测试
前端·react.js·前端框架
A3608_(韦煜粮)5 小时前
深入理解React Hooks设计哲学与实现原理:从闭包陷阱到并发模式
javascript·性能优化·react·前端开发·react hooks·并发模式·自定义hooks
5***o5005 小时前
React自动化测试
前端·react.js·前端框架