JAVASCRIPT
Implement a Custom `v-focus` Directive in Vue 3
Learn to create a reusable custom Vue 3 directive, `v-focus`, to automatically focus an input element when it's rendered or updated, enhancing user forms.
// 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()
},
// Called before the parent component is updated.
// This ensures re-focus if the element is re-rendered.
updated(el) {
el.focus()
}
})
app.mount('#app')
/* Usage in a Vue component:
<template>
<div>
<label for="nameInput">Name:</label>
<input v-focus id="nameInput" type="text" placeholder="I will be focused automatically">
</div>
</template>
<script setup>
// No script changes needed in the component itself for v-focus
</script>
*/
How it works: This snippet demonstrates how to create a custom directive named `v-focus` in Vue 3. Directives are a powerful way to add low-level DOM manipulation capabilities. When `v-focus` is applied to an HTML element, the `mounted` hook ensures the element is focused as soon as it's inserted into the DOM. The `updated` hook ensures it re-focuses if the component containing the element re-renders, providing a simple, declarative way to manage element focus programmatically without imperative DOM calls in component logic.