vuejs
/

Vue Custom Directives

Last Sync: Today

On this page

10
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

vuejs

Vue Custom Directives

What are Custom Directives?

Custom directives in Vue allow you to define reusable behavior that can be applied directly to DOM elements.

Why Use Custom Directives?

  • Encapsulate DOM logic
  • Reuse behavior across components
  • Extend Vue functionality
  • Handle low-level DOM operations

Basic Example

JavaScriptRead-only
1
app.directive('focus', {
  mounted(el) {
    el.focus();
  }
});

Usage in Template

HTMLRead-only
1
<input v-focus>

Directive Hooks

HookDescription
createdCalled before element is mounted
beforeMountBefore element is inserted
mountedWhen element is inserted
updatedWhen component updates
unmountedWhen element is removed

With Value

JavaScriptRead-only
1
app.directive('color', {
  mounted(el, binding) {
    el.style.color = binding.value;
  }
});

Usage with Value

HTMLRead-only
1
<p v-color="'red'">Hello</p>

Best Practices

  • Use directives only for DOM manipulation
  • Keep logic simple and reusable
  • Avoid business logic inside directives
  • Use components instead when possible

Common Mistakes

  • Using directives instead of components unnecessarily
  • Adding complex logic inside directives
  • Not cleaning up in unmounted hook
  • Misusing directive lifecycle hooks

Conclusion

Custom directives are useful for extending Vue functionality and handling direct DOM operations efficiently.

Try it yourself

app.directive('focus', { mounted(el) { el.focus(); } });

Test Your Knowledge

Q1
of 3

Custom directives used for?

A
Routing
B
DOM manipulation
C
API calls
D
Database
Q2
of 3

Which hook runs after mount?

A
created
B
mounted
C
updated
D
destroyed
Q3
of 3

binding.value is?

A
Directive name
B
Passed value
C
Element
D
Event

Frequently Asked Questions

What is a custom directive?

A reusable DOM behavior defined in Vue.

When to use directives?

For low-level DOM manipulation.

What is binding.value?

It contains the value passed to the directive.

Previous

vue v on

Next

vue components intro

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.