vue2 具体实现 首先el-table有提供两个事件cell-mouse-enter和cell-mouse-leave,这两个事件分别在当单元格 hover 进入时以及当单元格 hover 退出时会触发,回调函数中能接收四个参数:row, column, cell, event。 我们可以通过cell-mouse-enter事件,在鼠标进入到当前行的时候,根据第一个参数row判断当前行是否需要进行提示。如果需要提示的话,我们可以获取第四个参数event,拿到当前触发hover事件的dom元素。然后动态生成一个提示框div定位到鼠标右侧,插入到body中。 然后通过监听cell-mouse-leave事件将这个元素从body中移除。
// table组件
<el-table
:data="tableData"
style="width: 100%"
@cell-mouse-enter="enterSelectionRows"
@cell-mouse-leave="leaveSelectionRows"
>
// ......
</el-table>
`
// hover
enterSelectionRows (row, column, cell, event) {
console.log('enterSelectionRows hover', row, column, cell, event)
this.createTips(event, row, `名称:${row.name} <br />单号:${row.detailId} <br />开始日期:${row.startDate} <br />结束日期:${row.endDate}`)
},
leaveSelectionRows (row, column, cell, event) {
console.log('leaveSelectionRows leave', row, column, cell, event)
this.removeTips(row)
},
// 创建toolTip
createTips(el, row, value) {
const { detailId } = row
const tooltipDom = document.createElement('div')
tooltipDom.style.cssText = `
display: inline-block;
max-width: 400px;
max-height: 400px;
position: absolute;
top: ${el.clientY + 5}px;
left: ${el.clientX}px;
padding:5px 10px;
overflow: auto;
font-size: 14px;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: #595959;
background: #fff;
border-radius: 5px;
z-index: 19999;
box-shadow: 0 4px 12px 1px #ccc;
`
tooltipDom.innerHTML = value
tooltipDom.setAttribute('id', `tooltip-${detailId}`)
// 将浮层插入到body中
document.body.appendChild(tooltipDom)
},
// 删除tooltip
removeTips(row) {
const { detailId } = row
const tooltipDomLeave = document.querySelectorAll(`#tooltip-${detailId}`)
if (tooltipDomLeave.length) {
tooltipDomLeave.forEach(dom => {
document.body.removeChild(dom)
})
}
},