JAVASCRIPT

Vue 3 Custom Directive for Auto-Focus

Create a reusable custom Vue 3 directive to automatically focus an input element when a component is mounted or when the element becomes visible, improving UX.

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

const app = createApp(App)

app.directive('focus', {
  // When the bound element is inserted into the DOM...
  mounted(el) {
    el.focus()
  }
})

app.mount('#app')

// MyComponent.vue
<template>
  <div>
    <h2>Auto-Focus Example</h2>
    <input v-focus type="text" placeholder="I will be focused" />
    <input type="text" placeholder="I will not" />

    <button @click="showInput = !showInput">Toggle Input</button>
    <input v-if="showInput" v-focus type="text" placeholder="I will focus when visible" />
  </div>
</template>

<script setup>
import { ref } from 'vue'

const showInput = ref(false)
</script>
How it works: This snippet illustrates how to create and use a custom Vue 3 directive for auto-focusing elements. In `main.js`, `app.directive('focus', { mounted(el) { el.focus() } })` registers a global directive named `focus`. The `mounted` hook is called when the directive's element is inserted into the DOM. Inside this hook, `el.focus()` programmatically focuses the element. In `MyComponent.vue`, applying `v-focus` to an input element makes it automatically receive focus upon component mount or when the element is rendered conditionally via `v-if`, enhancing user experience.

Need help integrating this into your project?

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

Hire DigitalCodeLabs