import { h, render } from 'vue';
import { ElTooltip } from 'element-plus';
const processOverflow = (el, binding) => {
el.style.overflow = 'hidden';
el.style.textOverflow = 'ellipsis';
el.style.whiteSpace = 'nowrap';
// Determine if the textual content exceeds the container's width
if (el.scrollWidth <= el.clientWidth) return;
const textContent = el.innerText;
const tooltipMessage = binding.value || textContent;
// Clear existing child nodes
el.innerHTML = '';
// Construct the tooltip virtual node using a render function
const tooltipVNode = h(
ElTooltip,
{ content: tooltipMessage },
() => h('span', textContent)
);
render(tooltipVNode, el);
// Apply truncation styles to the newly appended element
const wrapper = el.firstElementChild;
if (wrapper) {
wrapper.style.display = 'block';
wrapper.style.width = '100%';
wrapper.style.overflow = 'hidden';
wrapper.style.textOverflow = 'ellipsis';
wrapper.style.whiteSpace = 'nowrap';
}
};
import { createApp } from 'vue';
import App from './App.vue';
const application = createApp(App);
application.directive('ellipsis-tip', {
mounted(el, binding) {
processOverflow(el, binding);
},
updated(el, binding) {
processOverflow(el, binding);
}
});
application.mount('#app');
<template>
<div style="width: 80px;" v-ellipsis-tip>Extremely long text content that exceeds the container dimensions</div>
<div style="width: 80px;" v-ellipsis-tip="'Hover to reveal this custom message'">Extremely long text content that exceeds the container dimensions</div>
</template>