处理element ui table组件加了 show-overflow-tooltip 后, 悬浮无法复制问题

1,435 阅读1分钟

直接复制到使用el-table组件的地方

import { getCell, getColumnByCell } from 'element-ui/packages/table/src/util'
import { getStyle, hasClass } from 'element-ui/src/utils/dom'
import { Table } from 'element-ui'
Object.assign(Table.components.TableBody.methods, {
  handleCellMouseLeave() {
    const tooltip = this.$refs.tooltip
    if (tooltip && tooltip.expectedState) {
      tooltip.setExpectedState(false)
      clearTimeout(tooltip._timeoutLeave)
      tooltip._timeoutLeave = setTimeout(() => {
        if (!tooltip.expectedState) {
          tooltip.handleClosePopper()
        }
      }, 150)
    }
    const cell = getCell(event)
    if (!cell) return

    const oldHoverState = this.table.hoverState || {}
    this.table.$emit(
      'cell-mouse-leave',
      oldHoverState.row,
      oldHoverState.column,
      oldHoverState.cell,
      event
    )
  },
  handleCellMouseEnter(event, row) {
    const table = this.table
    const cell = getCell(event)
    const tooltip = this.$refs.tooltip

    if (cell) {
      const column = getColumnByCell(table, cell)
      const hoverState = (table.hoverState = { cell, column, row })
      table.$emit('cell-mouse-enter', hoverState.row, hoverState.column, hoverState.cell, event)
    }

    // 判断是否text-overflow, 如果是就显示tooltip
    const cellChild = event.target.querySelector('.cell')
    if (!(hasClass(cellChild, 'el-tooltip') && cellChild.childNodes.length)) {
      setTimeout(() => {
        tooltip.setExpectedState(false)
        tooltip.handleClosePopper()
      }, 600)
      return
    }
    const range = document.createRange()
    range.setStart(cellChild, 0)
    range.setEnd(cellChild, cellChild.childNodes.length)
    const rangeWidth = range.getBoundingClientRect().width
    const padding =
      (parseInt(getStyle(cellChild, 'paddingLeft'), 10) || 0) +
      (parseInt(getStyle(cellChild, 'paddingRight'), 10) || 0)
    if (
      (rangeWidth + padding > cellChild.offsetWidth ||
        cellChild.scrollWidth > cellChild.offsetWidth) &&
      this.$refs.tooltip
    ) {
      // TODO 会引起整个 Table 的重新渲染,需要优化
      const showTooltip = () => {
        this.tooltipContent = cell.innerText || cell.textContent
        tooltip.referenceElm = cell
        tooltip.$refs.popper && (tooltip.$refs.popper.style.display = 'none')
        tooltip.doDestroy()
        tooltip.setExpectedState(true)
        this.activateTooltip(tooltip)
      }
      clearTimeout(tooltip._timeoutEnter)
      tooltip._timeoutEnter = setTimeout(() => {
        !tooltip.expectedState && showTooltip()
      }, 500)
    }
  }
})

const ElTable = { extends: Table }
// const ElTableColumn = { extends: TableColumn }

// 使用部分
components: {
    ElTable,
    // ElTableColumn,
  },

实现效果: 鼠标可以悬停到提示的信息上面, 并且能够复制 20240129164721

代码来源于网络, 是之前一个大佬写的, 给有缘人看, 少走点弯路, 其实这种问题就是elm的一个bug, 感觉不应该浪费过多时间在上面.