Implementing a Vue 3 Ellipsis Tooltip Custom Directive
javascript 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';
// Deetrmine 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 exitsing 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'; } };
javascript 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');
html