← Back to all snippets
JAVASCRIPT

Creating a Custom Vue 3 Directive for DOM Manipulation

Extend Vue 3's capabilities by building custom directives to directly manipulate the DOM or integrate third-party libraries with specific element bindings.

// main.js (or wherever your Vue app is created)
import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

// Register a global custom directive called 'v-focus'
app.directive('focus', {
  // When the bound element is mounted into the DOM...
  mounted(el) {
    el.focus(); // Focus the element
  },
  // You can also define other hooks like 'updated', 'beforeUnmount', etc.
  // updated(el, binding) {
  //   if (binding.value) {
  //     el.focus();
  //   }
  // }
});

app.mount('#app');

// MyComponent.vue
<template>
  <div>
    <p>Click the button to show an input that automatically gains focus:</p>
    <button @click="showInput = !showInput">Toggle Input</button>
    <input v-if="showInput" v-focus type="text" placeholder="I will gain focus automatically" />
  </div>
</template>

<script setup>
import { ref } from 'vue';

const showInput = ref(false);
</script>
How it works: Custom directives in Vue 3 are powerful tools for reusable low-level DOM manipulation. They allow developers to encapsulate specific DOM behaviors that are not covered by standard Vue directives. This snippet defines a global `v-focus` directive. When an element with `v-focus` is mounted into the DOM, the `mounted` hook is triggered, and `el.focus()` is called, causing the input field to automatically receive focus. This is particularly useful for accessibility or improving user experience in forms.

Need help integrating this into your project?

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

Hire DigitalCodeLabs