How to Create v-focus Directive in Vue: Simple Guide
In Vue, create a custom directive named
v-focus by defining a directive object with a mounted hook that calls el.focus(). Then register it globally or locally to automatically focus the element when it is inserted into the DOM.Syntax
The v-focus directive is created by defining an object with lifecycle hooks like mounted. The mounted hook receives the element el and focuses it using el.focus(). You then register this directive globally or locally in your Vue app.
javascript
const vFocus = { mounted(el) { el.focus(); } }; app.directive('focus', vFocus);
Example
This example shows a simple Vue app with an input field that automatically receives focus when the component is mounted using the v-focus directive.
vue
<template> <input v-focus placeholder="Focus is here automatically" /> </template> <script> import { createApp } from 'vue'; const vFocus = { mounted(el) { el.focus(); } }; const app = createApp({}); app.directive('focus', vFocus); app.mount('#app'); </script>
Output
An input box appears focused automatically when the page loads.
Common Pitfalls
- Trying to focus the element before it is in the DOM will not work; use the
mountedhook, notcreated. - For components that conditionally render inputs, ensure the directive is applied after the element appears.
- Do not use
insertedhook in Vue 3; usemountedinstead.
javascript
const vFocusWrong = { created(el) { // This won't work because element is not in DOM yet el.focus(); } }; const vFocusRight = { mounted(el) { el.focus(); } };
Quick Reference
Directive Hook: mounted(el) - called when element is inserted in DOM.
Action: el.focus() to set focus.
Registration: Use app.directive('focus', vFocus) for global or define in directives option for local.
| Concept | Description |
|---|---|
| mounted(el) | Hook to run code when element is in DOM |
| el.focus() | Focuses the element |
| app.directive('focus', vFocus) | Registers directive globally |
| v-focus usage | Use as to auto-focus input |
Key Takeaways
Use the mounted hook in your directive to access the element after it is in the DOM.
Call el.focus() inside mounted to set focus automatically.
Register the directive globally with app.directive or locally in component directives.
Avoid focusing elements too early, like in created hook, as they are not yet in the DOM.
Use v-focus on input elements to improve user experience by focusing them automatically.