DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • Creating Scrolling Text With HTML, CSS, and JavaScript
  • How to Create a Pokémon Breeding Gaming Calculator Using HTML, CSS, and JavaScript
  • Custom Elements Manifest: The Key to Seamless Web Component Discovery and Documentation

Trending

  • Why High-Performance AI/ML Is Essential in Modern Cybersecurity
  • Understanding and Mitigating IP Spoofing Attacks
  • Enhancing Security With ZTNA in Hybrid and Multi-Cloud Deployments
  • Automating Data Pipelines: Generating PySpark and SQL Jobs With LLMs in Cloudera
  1. DZone
  2. Coding
  3. JavaScript
  4. Custom Tooltip Directives in Vue.js 3

Custom Tooltip Directives in Vue.js 3

Learn about code reuse in Vue.js and how to take advantage of it for your implementations.

By 
Valerio Barbera user avatar
Valerio Barbera
·
Mar. 02, 23 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
4.0K Views

Join the DZone community and get the full member experience.

Join For Free

Custom directives in Vue.js 3 are one of those things where there is no compatibility with the previous version of the framework. 

Working on the new version of the Inspector frontend dashboard I had the need to show tooltips in many different points of the application.

Before entering the implementation of a custom tooltip directive in Vue.js 3 let me introduce the fundamentals of a good code reuse strategy in Vue.js.

Code Reuse in Vue.js

The most important forms for code reuse in Vue.js are components and composable if you write components with composition API.

The benefit of using components is that you can create complex user interfaces with ease, by breaking them down into smaller, reusable pieces. This makes it easier to maintain your code and allows you to make improvements to the user interface incrementally.

Vue.js provides other options for code reuse, such as mixins, directives, and plugins, which can further improve your code’s maintainability and reusability. Mixins are reusable code blocks that can be added to a component (no more recommended in Vue.js 3), while directives are used to add custom behavior to HTML elements. Plugins, on the other hand, are packages that can be installed and used across multiple components in your application.

By leveraging these features, you can create powerful, scalable applications that are easy to maintain and extend.

If you want to learn more strategies used to build our platform check out this article on how to implement an event bus in Vue.js 3: https://inspector.dev/why-and-how-to-create-an-event-bus-in-vuejs-3/

Custom Directives in Vue.js 3

As mentioned in the documentation:

Custom directives, on the other hand, are mainly intended for reusing logic that involves low-level DOM access on plain elements.

A perfect tool to add features like “tooltip”, “popover” and other Bootstrap components to DOM elements.

A directive in Vue.js is essentially an object with the same properties and hooks used in components. But in this case, the hooks will receive the instance of the DOM element the directive is bound to.

JavaScript
 
export default {
    mounted(el) {
        el.focus();
    }
}


To register the directive and make it available in the template you must pass the directive object to the app instance: 

JavaScript
 
const app = createApp({})

import tooltip from "./Directives/tooltip";

// make v-tooltip usable in all components
app.directive('tooltip', tooltip);


You can check out all the available lifecycle hooks in the official documentation. 

Custom Tooltip Directive for Vue.js 3

Why do we need to create a directive to show tooltips?

As mentioned in the Bootstrap 5 documentation you have to initialize Tooltips with javascript to make it visible:

JavaScript
 
// HTML in your view
<a href="#" data-bs-toggle="tooltip" data-bs-title="Hello World!">Tooltip Example</a>


// Enable tooltip via Javascript 
const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');

const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));


But this code works in a static HTML page, where DOM elements are available yet the time the javascript code runs to activate all the tooltips in the view.

But a reactive frontend application works in the opposite way. Components are loaded dynamically with the user interaction. So every tooltip included in the view after the first application bootstrap will not be activated and will remain hidden.

We need to attach tooltips to the DOM elements dynamically at the time the element is attached to the view.

A perfect use case for a custom directive in Vue.js.

JavaScript
 
import {Tooltip} from "bootstrap";

// Use "mounted" hook
export default {
    mounted(el, binding) {
        let tooltip = new Tooltip(el, {
            placement: binding.arg || 'top',
            title: binding.value
        });
    }
}


Register the directive in the app instance to make it available in your components: 

JavaScript
 
import tooltips from "./Directives/tooltips.js";
app.directive(tooltips);

How to Use the Tooltip Directive

The code above allows you to set the behavior of the tooltip dynamically.

Default usage:

HTML
 
<a href="#" v-tooltip="Hello World!">Tooltip Example</a>

If you want to change the placement of the tooltip you can pass it as an argument: 

HTML
 
<a href="#" v-tooltip:right="Hello World!">Tooltip Example</a>

Conclusion

I hope this article can help you design your software products in a more convenient way. This implementation can be replicated for popover and other Bootstrap components.

HTML JavaScript Vue.js

Published at DZone with permission of Valerio Barbera. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • Creating Scrolling Text With HTML, CSS, and JavaScript
  • How to Create a Pokémon Breeding Gaming Calculator Using HTML, CSS, and JavaScript
  • Custom Elements Manifest: The Key to Seamless Web Component Discovery and Documentation

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!