JAVASCRIPT

Create a Custom `v-focus` Directive in Vue 3

Implement a custom Vue 3 directive, `v-focus`, to automatically set focus on an input field or any focusable DOM element when it's rendered.

// main.js (or a plugin file)
import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

app.directive('focus', {
  // Called when the bound element's parent component and all its children
  // are mounted.
  mounted(el) {
    el.focus();
  }
  // You can also define other hooks like updated, beforeUnmount, etc.
});

app.mount('#app');


// App.vue (Example Usage)
<template>
  <div>
    <p>This input will auto-focus on load:</p>
    <input v-focus type="text" placeholder="I'm focused!" />

    <p>This input will not:</p>
    <input type="text" placeholder="Not focused" />

    <p>A button that can also be focused:</p>
    <button v-focus>Focus Button</button>
  </div>
</template>

<script setup>
// No script needed here for v-focus directive usage
</script>
How it works: This snippet illustrates how to create a custom directive in Vue 3. The `v-focus` directive is defined globally in `main.js` using `app.directive()`. Its `mounted` hook is triggered once the element is inserted into the DOM, programmatically calling the `focus()` method on that element. This provides a declarative and reusable way to automatically focus elements, enhancing user experience for forms or specific interactive elements.

Need help integrating this into your project?

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

Hire DigitalCodeLabs