JAVASCRIPT

Creating Custom Directives for DOM Manipulation in Vue 3

Extend Vue 3's capabilities by building custom directives to directly manipulate the DOM, perfect for tasks like focusing inputs or applying specific styles.

// main.js (or any setup file)
import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

// Define a custom directive 'v-focus'
app.directive('focus', {
  // Called when the bound element's attributes or children change
  updated(el) {
    el.focus();
  },
  // Called when the bound element is inserted into the DOM
  mounted(el) {
    el.focus();
  }
});

app.mount('#app');

// MyComponent.vue
<template>
  <div>
    <label>Auto-focused Input:</label>
    <input type="text" v-focus>

    <label>Another Input:</label>
    <input type="text">

    <label>Conditional Focus:</label>
    <input type="text" v-focus="shouldFocus">
    <button @click="shouldFocus = !shouldFocus">Toggle Focus</button>
  </div>
</template>

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

const shouldFocus = ref(false);
</script>
How it works: This snippet shows how to create and use a custom directive in Vue 3. The `app.directive()` method is used to register a directive globally. Here, the `v-focus` directive automatically focuses an input element when it's mounted to the DOM or if its value changes (using `updated`). Directives expose various hook functions like `mounted` and `updated` that receive the element (`el`) as an argument, allowing direct DOM manipulation. The second input demonstrates passing a boolean value to the directive, which can be used for conditional behavior within the directive's logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs