使用到 Element–Table 中的 show-overflow-tooltip=“true” 实现文本内容过长时显示省略号及 tooltip 提示框,需求有提到:在提示框内是需要可以复制的,直接使用现况是 做不到把鼠标移入提示框内,更不用提复制了
方法一:如果是二次封装 element 组件的话,可以在封 table-column 时覆盖下
方法二: 更改 element 源码(简略)
// ~/table/src/table-column.js
// 配置 table 的 column 时,判断 showOverflowTooltip 属性添加 el-tooltip 的类名
setColumnRenders(column) {
if (column.showOverflowTooltip) {
props.class += ' el-tooltip';
props.style = {width: (data.column.realWidth || data.column.width) - 1 + 'px'};
}
}
// ~/table/src/table-body.js
created() {
// 这里用了个防抖函数包裹起来
this.activateTooltip = debounce(50, tooltip => tooltip.handleShowPopper());
}
// 这里是表格 cell 鼠标移入的方法
handleCellMouseEnter(event, row) {
// 判断是否text-overflow, 如果是就显示tooltip
const cellChild = event.target.querySelector('.cell');
if (!(hasClass(cellChild, 'el-tooltip') && cellChild.childNodes.length)) {
return;
}
if ((rangeWidth + padding > cellChild.offsetWidth || cellChild.scrollWidth > cellChild.offsetWidth) && this.$refs.tooltip) {
const tooltip = this.$refs.tooltip;
// TODO 会引起整个 Table 的重新渲染,需要优化
this.tooltipContent = cell.innerText || cell.textContent;
tooltip.referenceElm = cell;
tooltip.$refs.popper && (tooltip.$refs.popper.style.display = 'none');
tooltip.doDestroy();
tooltip.setExpectedState(true);
// 显示 tooltip
this.activateTooltip(tooltip);
}
}
// 这里是表格 cell 鼠标移出的方法,可以看到,如果有 tooltip 时,会执行tooltip的setExpectedState,handleClosePopper两个方法
handleCellMouseLeave(event) {
const tooltip = this.$refs.tooltip;
if (tooltip) {
tooltip.setExpectedState(false);
// 隐藏 tooltip
tooltip.handleClosePopper();
}
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);
}
// ~/tooltip/src/main.js
beforeCreate() {
this.debounceClose = debounce(200, () => this.handleClosePopper());
}
// tooltip 是否显示
handleShowPopper() {
if (!this.expectedState || this.manual) return;
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
this.showPopper = true;
}, this.openDelay);
if (this.hideAfter > 0) {
this.timeoutPending = setTimeout(() => {
this.showPopper = false;
}, this.hideAfter);
}
},
handleClosePopper() {
// 这里是通过三个状态值来判断是否展示
if (this.enterable && this.expectedState || this.manual) return;
clearTimeout(this.timeout);
if (this.timeoutPending) {
clearTimeout(this.timeoutPending);
}
this.showPopper = false;
if (this.disabled) {
this.doDestroy();
}
},
// 这个是设置主要状态的一个方法,每次是否显示 tooltip 之前都要调用此方法将 expectedState 状态置为 true/false
setExpectedState(expectedState) {
if (expectedState === false) {
clearTimeout(this.timeoutPending);
}
this.expectedState = expectedState;
},
解决
将 handleCellMouseLeave 的 tooltip.handleClosePopper() 替换成 tooltip.debounceClose() 让这个行为有一个延时的动作再去关闭,这样在移入移出过程中,tooltip 就不会立马关闭掉了