JAVASCRIPT

Extending Vue with Custom Directives (v-focus)

Learn how to create and register custom Vue 3 directives, like a `v-focus` directive, to add reusable low-level DOM manipulation directly to your elements.

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

// src/main.js (Registering globally)
import { createApp } from 'vue';
import App from './App.vue';
import { vFocus } from './directives/VFocus';

const app = createApp(App);

// Register a global custom directive called `v-focus`
app.directive('focus', vFocus);

app.mount('#app');

// src/components/AutoFocusInput.vue (Usage Example)
<template>
  <div>
    <label for="nameInput">Your Name:</label>
    <input type="text" id="nameInput" v-focus placeholder="Enter your name">
    <p>The input above will automatically gain focus when this component is mounted.</p>
  </div>
</template>

<script setup>
// No script needed for v-focus usage, it's applied via template.
// If you need to use local registration:
// import { vFocus } from '../directives/VFocus';
// const directives = { focus: vFocus };
</script>
How it works: This snippet demonstrates creating and using a custom Vue 3 directive `v-focus`. The directive is defined as an object with a `mounted` hook, which is called when the bound element is inserted into the DOM. Inside this hook, `el.focus()` is called to automatically focus the input element. The directive is then globally registered in `main.js` using `app.directive()`, allowing it to be used declaratively as `v-focus` on any element in the application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs