写一个 混入 之前用全局监听总觉得,太耗性能了。而且也不好销毁。
引入下面tooltipMixin.js,混入注册:mixins: [tooltipMixin], 数据请求完成后 在nextTick 方法中传入需要绑定的 dom ,
import tooltipMixin from '@/mixins/tooltipMixin'
mixins: [tooltipMixin],
this.$nextTick(()=>{
let content = this.$el.querySelector('.list')
this.tooltipInit(content)
})
const parentDom = document.body;
export default {
data() {
return {
tooltip: null,
target: null,
customDom: null,
timeout: null,
};
},
watch: {
tooltip(val) {
if (val) {
val.addEventListener("mouseover", (e) => {
clearTimeout(this.timeout);
});
val.addEventListener("mouseleave", (e) => {
this.timeout = setTimeout(() => {
this.tooltip && this.tooltip.remove();
}, 100);
});
}
},
target(val) {
if (val) {
val.removeEventListener("mouseleave", this.removeDom);
val.addEventListener("mouseleave", this.removeDom);
}
},
},
mounted() {
},
methods: {
tooltipInit(dom) {
if (!dom) {
return;
}
this.customDom = dom;
this.customDom.addEventListener("mouseover", this.handleOver);
},
handleOver(e) {
var target = e.target;
if (target.getAttribute("tooltip")) {
this.tooltip && this.tooltip.remove();
clearTimeout(this.timeout);
let tooltipText = target.getAttribute("tooltip");
let targetObj = target.getBoundingClientRect();
const tooltip = document.createElement("div");
const tooltipContent = document.createElement("div");
tooltip.className = "tooltipCls";
tooltipContent.innerHTML = tooltipText;
tooltip.appendChild(tooltipContent);
tooltipContent.style.cssText = `
max-height: 380px;
max-width: 100%;
overflow: auto;
`;
parentDom.appendChild(tooltip);
this.tooltip = tooltip;
tooltip.style.cssText = `
display: inline-block;
max-width: 500px;
max-height: 400px;
position: absolute;
top: ${targetObj.top - 8}px;
left: ${targetObj.left + parseFloat(targetObj.width) / 2}px;
padding: 10px;
font-size: 14px;
color: #fff;
background: #303133;
border-radius: 5px;
z-index: 19999;
transform: translate(-50%, -100%);
transform-origin: center bottom;
transition: all 0.3s
`;
this.target = target;
}
},
removeDom(e) {
const tooltipObj = this.tooltip.getBoundingClientRect();
let inToolTip = false;
if (
e.pageY >= tooltipObj.top &&
e.pageY <= tooltipObj.bottom &&
e.pageX >= tooltipObj.left &&
e.pageX <= tooltipObj.right
) {
inToolTip = true;
} else {
inToolTip = false;
}
if (!inToolTip) {
this.timeout = setTimeout(() => {
this.tooltip && this.tooltip.remove();
}, 100);
}
},
},
beforeDestroy() {
this.customDom &&
this.customDom.removeEventListener("mouseover", this.handleOver);
},
};
css
// 自定义 tooltip 功能 三角样式
.tooltipCls::after {
content: '';
position: absolute;
left: 50%;
bottom: 0px;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 8px;
border-top-color: #303133;
transform: translate(-50%, 100%);
transform-origin: center bottom;
}