We are already familiar with Vue's built-in v-if and v-model directives.
A directive is a special attribute with the v- prefix that declaratively manipulates the DOM when applied to an HTML element.
What if we need DOM behavior that Vue does not provide?
For example, a particular input may need focus automatically as soon as the page loads.
This is where a
The code defines a vFocus object and uses the mounted hook.
The hook runs immediately after the <input> element receiving the directive appears on screen.
It receives that element as el and simply calls el.focus().
Custom directives are useful when you need to step outside Vue's declarative templates and manipulate a particular DOM element directly.
Applications often repeat identical logic across components.
Examples include tracking mouse coordinates, observing window-size changes, and fetching API data.
Copying this logic into every component is inefficient.
Vue 3's Composition API offers an elegant solution:
composables
.
A composable is
a function that uses Vue's reactivity APIs to encapsulate and reuse stateful logic
.
By convention, its name starts with use.
Let's create the useMouse composable to track mouse position.
Create a src/composables folder and add useMouse.ts.
We learned two ways to improve code reuse in Vue applications.
Custom directives
Use them for direct, low-level manipulation of a particular DOM element.
They work well for encapsulating focused DOM behaviors such as v-focus.
Composables
Vue 3's standard approach to reusing stateful logic.
This flexible pattern can fetch data, track events, interact with browser APIs, and handle many other tasks.
When you see repeated logic, ask whether it could become a composable.
Extra Part 2 explores Slot and Teleport, which make components more flexible.