0 day streak
javascript / intermediate
Snippet

Implementing Custom Directives for DOM Access

Custom directives allow you to reuse low-level DOM logic across components. In <script setup>, any camelCase variable starting with 'v' is automatically recognized as a directive that can be used in the template.

snippet.js
javascript
1
2
3
const vFocus = {
mounted: (el) => el.focus()
};
vue
Breakdown
1
const vFocus = {
Define a directive object following the naming convention 'v' + Name.
2
mounted: (el) => el.focus()
The lifecycle hook 'mounted' receives the target DOM element and calls the native focus method.