JAVASCRIPT

Create a Custom Directive in Vue 3

Learn to extend Vue's capabilities by creating custom directives for reusable DOM manipulation, like an autofocus directive, in Vue 3 applications.

// src/directives/VAutofocus.js
export const VAutofocus = {
  mounted: (el) => {
    el.focus();
  },
};

// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import { VAutofocus } from './directives/VAutofocus';

const app = createApp(App);
app.directive('autofocus', VAutofocus);
app.mount('#app');

// src/App.vue
<template>
  <div>
    <label for="username">Username:</label>
    <input type="text" id="username" v-autofocus />
    <label for="email">Email:</label>
    <input type="email" id="email" />
  </div>
</template>

<script setup></script>
How it works: This snippet illustrates how to create and register a custom directive in Vue 3. A directive is a reusable piece of logic that can be applied to elements in the template to perform low-level DOM manipulation. The `VAutofocus` directive is defined with a `mounted` hook, which is called when the element is inserted into the DOM. It programmatically calls `focus()` on the input element, automatically making it active when the component renders. Directives are registered globally in `main.js` and then used with a `v-` prefix in any component.

Need help integrating this into your project?

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

Hire DigitalCodeLabs