Vue Custom Directives: For Low-Level DOM Access
Vue custom directives are for low-level DOM access. Use them for tasks like auto-focusing a dynamically inserted input. The footgun is using them for stateful logic or UI structure, where a composable or component is the right tool.
WHY IT EXISTS While Vue provides components for UI structure and composables for stateful logic, sometimes you need to drop down a level and directly manipulate a DOM element. Custom directives provide a structured, reusable way to do this within the Vue ecosystem, keeping your code clean.
THE MENTAL MODEL Think of custom directives as a dedicated tool for direct DOM manipulation. They are the Vue-native way to handle tasks that would otherwise require manual DOM queries. While components build UI and composables manage logic, directives are for when you just need to call element.focus() or add a special class after an element is mounted.
HOW IT WORKS A custom directive is an object containing lifecycle hooks, like mounted. These hooks receive the element the directive is bound to. In <script setup>, a camelCase variable starting with v (e.g., vFocus) is automatically available in the template as a directive (e.g., v-focus). You can also register them globally on the app instance or locally in a component's directives option.
WHEN TO USE IT Use a custom directive only when the functionality requires direct DOM manipulation. A classic case is an auto-focus feature for an input that appears conditionally. The standard HTML autofocus attribute only works on page load, but a v-focus directive works whenever Vue inserts the element into the DOM.
WHEN NOT TO USE IT Avoid directives for logic that can be handled by components or composables. If you're managing state or creating a reusable piece of UI, a directive is the wrong tool. Overusing them for non-DOM tasks makes code harder to understand and maintain. Stick to their intended purpose: low-level DOM access.
ONE CANONICAL EXAMPLE The v-focus directive is a perfect example of why directives are useful. It solves a problem that the native autofocus attribute cannot: focusing an element that is dynamically added to the page. The implementation is simple: const vFocus = { mounted: (el) => el.focus() }. In a template, you'd use it like this: <input v-focus />. Whenever this input is mounted by Vue, it will immediately gain focus.
Read the original → vuejs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.