← Back to all snippets
JAVASCRIPT

Vue 3 Custom Directives for DOM Manipulation

Extend Vue 3's functionality by creating a custom directive, such as an auto-focus directive, to encapsulate reusable direct DOM manipulation logic.

// main.js or main.ts
import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

// Define a global custom directive 'v-focus'
app.directive('focus', {
  // When the bound element is mounted into the DOM...
  mounted(el) {
    el.focus();
  },
  // You can define other hooks like updated, beforeUnmount etc.
  // updated(el, binding) {
  //   if (binding.value) {
  //     el.focus();
  //   }
  // }
});

app.mount('#app');

// App.vue (or any component)
<template>
  <div>
    <h1>Custom Directive Example</h1>
    <p>The input below will automatically focus when the component is mounted.</p>
    <input type="text" v-focus placeholder="I'm auto-focused!" />

    <p>Another input for comparison:</p>
    <input type="text" placeholder="I'm not auto-focused" />
  </div>
</template>

<script setup>
// No script needed for v-focus directive usage here, 
// as it's globally registered.
</script>
How it works: This snippet shows how to create and use a custom directive in Vue 3. The `v-focus` directive is globally registered in `main.js` using `app.directive()`. The directive object defines lifecycle hooks, such as `mounted`, which is called when the element is inserted into the DOM. Inside `mounted`, `el.focus()` is called, causing the input field to automatically gain focus. This allows for encapsulating reusable direct DOM manipulations in a declarative way.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs