Skip to content

Instantly share code, notes, and snippets.

@ForwardFeed
Last active July 26, 2025 16:02
Show Gist options
  • Select an option

  • Save ForwardFeed/2ab550e555ff0917e134ef38603dfd6a to your computer and use it in GitHub Desktop.

Select an option

Save ForwardFeed/2ab550e555ff0917e134ef38603dfd6a to your computer and use it in GitHub Desktop.
Vue3 TS, Custom Directive (tooltip example)
# based on a tooltip directive, the most common use of custom directive
//[...]
import tooltip_directive from './tooltip_directive'
const app = createApp(App)
// you must register it, tooltip will be transformed into the directive: v-tooltip
app.directive("tooltip", tooltip_directive)
//[...]
<script lang="ts" setup>
// use the directive with: v-tooltip
</script>
<template>
<button class="border" v-tooltip="{text: 'some text', color: 'red-200'}">
<span>{{ text }}</span>
</button>
</template>
export type Tooltip = {
text: string,
color: string,
//any_other_stuff you want
}
// Here specify in the generic Tooltip
export const tooltip_directive: Directive<HTMLElement, Tooltip> = {
// I show as mounted ,but there is all the regular lifecycle hooks in it.
mounted (el, { value: tooltip_data }, vnode) {
el.addEventListener('mouseover', function(ev: Event){
// popup spawn with the tooltip_data.text and tooltip_data.color
})
el.addEventListener('mouseout', function(ev: Event){
// clean up popup spawn
})
},
// quick tips, if you don't do that same function but for updated lifecycle hook
// you may encounters vue optimizations that instead of
// replacing a component from scratch it actuals sends an update with the new values
// but for directives it may often means that it's like a new comps has been remounted
updated(el, { value: tooltip }, vnode) {
el.addEventListener('mouseenter', function(){
// popup spawn with the tooltip_data.text and tooltip_data.color
})
el.addEventListener('mouseleave', function(){
// clean up popup spawn
})
},
}
// needed for typescript support, so if you get it wrong in your vue calls, it will show up
// If you forget that, then you will have no type support
declare module 'vue' {
interface ComponentCustomProperties {
vTooltip: typeof tooltip_directive
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment