javascript / intermediate
Snippet
DOM Manipulation via Custom Directives
Custom directives provide a way to reuse low-level DOM access logic across your application. By defining a directive object with lifecycle hooks like 'mounted', you can directly manipulate elements, such as triggering an input focus automatically when a component is rendered.
snippet.js
1
2
3
4
5
6
7
8
const vFocus = {mounted: (el) => {el.focus();}};// Usage in template:// <input v-focus />
vue
Breakdown
1
const vFocus = { ... };
Naming the variable starting with 'v' allows it to be used as a directive in script setup.
2
mounted: (el) => { ... }
A hook that executes once the element is attached to the DOM tree.
3
el.focus();
Standard JavaScript DOM method to set the focus on the target element.