JAVASCRIPT
Building Custom Directives in Vue 3 (v-focus)
Master creating custom directives in Vue 3 to directly manipulate the DOM, enabling reusable behavioral logic like auto-focusing an input element upon render.
// main.js (Global registration)
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
app.directive('focus', {
mounted(el) {
el.focus();
}
});
app.mount('#app');
// MyComponent.vue
<template>
<div>
<h1>Custom Directive Example</h1>
<p>This input will automatically focus when the component is mounted:</p>
<input type="text" v-focus placeholder="I'm focused!" />
<p>Another input (not focused):</p>
<input type="text" placeholder="Not focused" />
</div>
</template>
<script setup>
// For local registration in a component:
/*
const vFocus = {
mounted: (el) => el.focus()
}
*/
</script>
How it works: This snippet demonstrates how to create a custom directive in Vue 3. The `v-focus` directive is globally registered in `main.js`. It defines a `mounted` hook that is called when the element it's bound to is inserted into the DOM. Inside this hook, `el.focus()` is called, causing the input field to automatically gain focus upon component render. This allows for direct, reusable DOM manipulation logic.