Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing a Vue 3 Ellipsis Tooltip Custom Directive

Tech Apr 19 37
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>

Related Articles

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.