JAVASCRIPT

Enhance Vue 3 Components with Custom Directives

Discover how to create and register custom directives in Vue 3 Composition API to encapsulate reusable DOM manipulation logic, improving code modularity and reusability.

// directives/vFocus.js
export const vFocus = {
  mounted: (el) => el.focus()
};

// main.js
import { createApp } from 'vue';
import App from './App.vue';
import { vFocus } from './directives/vFocus';

const app = createApp(App);

// Register a global custom directive
app.directive('focus', vFocus);

app.mount('#app');

// App.vue
<template>
  <div>
    <p>Click the button to show the input, then it will autofocus:</p>
    <button @click="showInput = !showInput">Toggle Input</button>
    <input v-if="showInput" v-focus type="text" placeholder="I will autofocus!">

    <p>Another example: a custom `v-color` directive</p>
    <div v-color="'blue'">This text is blue.</div>
    <div v-color="myColor">This text is {{ myColor }}.</div>
  </div>
</template>

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

const showInput = ref(false);
const myColor = ref('green');

// Local directive definition (optional, if not globally registered)
const vColor = {
  mounted: (el, binding) => {
    el.style.color = binding.value;
  },
  updated: (el, binding) => {
    el.style.color = binding.value;
  }
};
</script>

<style scoped>
/* Some styling */
</style>
How it works: Custom directives allow developers to abstract reusable DOM manipulation logic that needs to be applied repeatedly across different components. This example shows how to create a `v-focus` directive that automatically focuses an input element when it's mounted. It also demonstrates how to register directives globally in `main.js` and locally within a component, and how to use directive arguments and values (`v-color="'blue'"` or `v-color="myColor"`) to make them dynamic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs