JAVASCRIPT

Implement Custom Directives for Advanced DOM Manipulation in Vue 3

Create custom Vue 3 directives to encapsulate low-level DOM manipulation, such as focusing elements or handling specific attribute bindings, cleanly.

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

const app = createApp(App);

// Register a custom directive globally
app.directive('focus', {
  mounted(el) {
    el.focus(); // Focus the element when it's mounted
  },
  updated(el, binding) {
    // Optional: Focus only if the binding value is true
    if (binding.value) {
      el.focus();
    }
  }
});

app.mount('#app');

// App.vue (or any component)
<template>
  <div>
    <h1>Custom Focus Directive</h1>
    <label>
      Always focused input:
      <input v-focus type="text" />
    </label>
    <br /><br />
    <label>
      Conditionally focused input:
      <input v-focus="shouldFocus" type="text" placeholder="Click button to focus" />
    </label>
    <button @click="shouldFocus = !shouldFocus">Toggle Focus</button>
  </div>
</template>

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

const shouldFocus = ref(false);
</script>
How it works: Custom directives in Vue 3 provide a way to encapsulate low-level DOM manipulation that might be specific to your application. This example defines a `v-focus` directive. When applied to an HTML element, its `mounted` hook is called, automatically focusing that element. The `updated` hook allows for conditional focus based on a binding value, demonstrating how directives can react to data changes. Directives are registered globally using `app.directive()` or locally within a component.

Need help integrating this into your project?

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

Hire DigitalCodeLabs