← Back to all snippets
JAVASCRIPT

Building Custom Directives in Vue 3

Learn to extend Vue 3's capabilities by creating custom directives like `v-focus`, enabling direct DOM manipulation for specific behaviors and enhanced user experience.

import { createApp, ref } from 'vue';

const app = createApp({
  template: `
    <div>
      <p>Click outside the input to lose focus, then click the button.</p>
      <input type="text" v-focus="isFocused" placeholder="I will be focused" />
      <button @click="toggleFocus">Toggle Focus</button>
    </div>
  `,
  setup() {
    const isFocused = ref(false);
    const toggleFocus = () => {
      isFocused.value = !isFocused.value;
    };
    return { isFocused, toggleFocus };
  }
});

// Register a global custom directive called v-focus
app.directive('focus', {
  // Called when the bound element has been mounted into the DOM.
  mounted(el, binding) {
    if (binding.value) {
      el.focus();
    }
  },
  // Called before the bound element's attributes or children are updated.
  updated(el, binding) {
    if (binding.value) {
      el.focus();
    }
  }
});

// To run this code, mount the app:
// app.mount('#app');
How it works: This snippet demonstrates how to create and use a custom directive in Vue 3, specifically `v-focus`. Custom directives allow you to abstract low-level DOM manipulations into reusable behaviors. The `focus` directive uses the `mounted` hook to set initial focus when the element appears, and the `updated` hook to re-focus if its bound value changes. This provides a clean way to manage specific DOM interactions directly from your templates.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs