创建js文件
export default {
bind(el, { value }, vnode) {
const curStyle = window.getComputedStyle(el, "");
const textSpan = document.createElement("span");
let num = parseInt(Math.random() * 1000);
vnode.key = num;
textSpan.style.fontSize = curStyle.fontSize;
textSpan.style.fontWeight = curStyle.fontWeight;
textSpan.style.fontFamily = curStyle.fontFamily;
document.body.appendChild(textSpan);
textSpan.innerHTML = el.innerText;
if (textSpan.offsetWidth > el.offsetWidth) {
el.style.overflow = "hidden";
el.style.textOverflow = "ellipsis";
el.style.whiteSpace = "nowrap";
el.onmouseenter = function (e) {
const vcTooltipDom = document.createElement("div");
vcTooltipDom.style.cssText = `
max-width:400px;
max-height: 400px;
overflow: auto;
position:fixed;
top:${e.clientY + 5}px;
left:${e.clientX}px;
background: #000;
color:#fff;
border-radius:5px;
padding:10px;
display:inline-block;
font-size:12px;
z-index:19999
`;
vcTooltipDom.setAttribute("id", "vc-tooltip");
document.body.appendChild(vcTooltipDom);
document.getElementById("vc-tooltip").innerHTML = el.innerText;
};
el.onmouseleave = function () {
const vcTooltipDom = document.getElementById("vc-tooltip");
vcTooltipDom && document.body.removeChild(vcTooltipDom);
};
}
document.body.removeChild(textSpan);
},
};
src\directive\index.js文件引入
import showTips from './js/showTips';
const directives = {
showTips
}
export default {
install(Vue){
Object.keys(directives).forEach(key=>{
Vue.directive(key, directives[key])
})
}
}
main.js引入
import Directives from "@/directive/index";
Vue.use(Directives);
使用
<p v-showTips style="width:250px">测试长度</p>
此方法有个问题,需要显示省略号的数据是接口调用的,所以一开始加载界面时数据还没出来,文字未超出的时候移入也会显示提示框