Thuta Learning
IntermediateWeb Developmentbeginner

Custom Directives and Plugins

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Work with the custom directive lifecycle
  • Choose between a directive and a component
  • Register a plugin

Let's break it down simply

Only reach for a custom directive when you need to reuse low-level DOM behavior. If UI structure is involved, a component or composable is usually the better fit. Use a plugin's install(app) to bundle up app-wide services and directives.

vue
<script setup>
const vFocus = {
  mounted(element) {
    element.focus()
  }
}
</script>

<template>
  <label>
    Search
    <input v-focus placeholder="Type to search">
  </label>
</template>
You should see
Search input receives focus after mount

Try it yourself

Write a v-click-outside custom directive that calls a callback when you click outside the element.

Custom DirectivesVue.js

Easy traps

  • Overcomplicating plain template logic by turning it into a directive
  • Not cleaning up a directive's event listener in the unmounted hook

Exercise

Write a v-click-outside custom directive that calls a callback when you click outside the element.

You'll know it worked when: Search input receives focus after mount