JAVASCRIPT

Develop a Custom Vue 3 Directive for Enhanced DOM Interaction

Learn to create a custom Vue 3 directive (e.g., `v-focus`) to abstract and reuse low-level DOM manipulations, such as automatically focusing an input element, enhancing user experience and code modularity.

// main.js (or wherever your app is mounted)
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, binding) {
    // Focus the element
    if (binding.value !== false) { // Allows v-focus="false" to disable
      el.focus();
      if (binding.arg === 'select') { // v-focus:select
        el.select();
      }
    }
  },
  updated(el, binding) {
    // Re-focus if value changes to true
    if (binding.value && !binding.oldValue) {
       el.focus();
    }
  }
});

app.mount('#app');

// App.vue
<template>
  <div>
    <h1>Custom Directive Example</h1>
    <p>Automatically focused input:</p>
    <input v-focus type="text" placeholder="I am focused automatically">

    <p>Selectable input:</p>
    <input v-focus:select="true" type="text" value="This text is selected">

    <p>Conditional focus:</p>
    <input v-focus="shouldFocus" type="text" placeholder="Focus me conditionally">
    <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 demonstrates how to create and register a custom Vue 3 directive, `v-focus`, for direct, reusable DOM manipulation. The directive is registered globally and includes a `mounted` hook that automatically focuses the bound input element when it's added to the DOM. It also showcases how to accept arguments (e.g., `v-focus:select` to select text) and values (e.g., `v-focus="shouldFocus"` for conditional application), making the directive highly flexible. Custom directives are ideal for encapsulating low-level, direct DOM interactions that don't fit naturally into component logic, providing a declarative way to extend HTML element behavior.

Need help integrating this into your project?

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

Hire DigitalCodeLabs