DEV Community

Cover image for How to Register Custom Directives in Nuxt 3
Dawit
Dawit

Posted on • Originally published at minch.dev

1 1

How to Register Custom Directives in Nuxt 3

TL;DR

Create a plugin file in your plugins/ directory, which is where we'll have access to our Vue app instance.

We can define and register our custom directive there:

// ~/plugins/my-directives.ts
export default defineNuxtPlugin((nuxtApp) => {
    nuxtApp.vueApp.directive('highlight', {
        mounted(el, binding) {
            el.style.backgroundColor = binding.value
        }
    });

    // Register more directives as needed
});
Enter fullscreen mode Exit fullscreen mode

In Detail

In Vue, directives are special attributes on HTML elements that are used to extend and manipulate their behavior. Vue provides several built-in directives:

  • v-bind - used to dynamically bind an attribute to a JavaScript expression,
  • v-on - used to attach event listeners to elements,
  • v-if/v-else-if/v-else - used to conditionally render elements,
  • and so much more.

For more specific and advanced use cases, Vue provides a way to create custom directives. These can be particularly useful for lower-level DOM manipulations.

In a plain Vue app, to register custom directives at the app level, we can attach it to our app instance as such:

const app = creatApp({});

app.directive('highlight', {
    mounted(el, binding) {
        el.style.backgroundColor = binding.value
    }
});
Enter fullscreen mode Exit fullscreen mode

We can then use the directive on any element globally within our app:

<p v-highlight="'yellow'">This text will be highlighted!</p>
Enter fullscreen mode Exit fullscreen mode

How about in Nuxt?

To achieve the same functionality in Nuxt, we will need access to our Vue app instance, and we can use a plugin to do so.

Plugins in Nuxt can be used to add functionality to an application at the Vue app level. They get loaded and executed when the Vue app is created, and files inside the plugins/ directory of a Nuxt app are automatically registered as plugins by Nuxt.

In Nuxt, we can create a plugin file in the plugins/ directory, which we can use to globally define and register our custom directives:

// ~/plugins/my-directives.ts
export default defineNuxtPlugin((nuxtApp) => {
    nuxtApp.vueApp.directive('highlight', {
        mounted(el, binding) {
            el.style.backgroundColor = binding.value
        }
    });

    // Register more directives as needed
});
Enter fullscreen mode Exit fullscreen mode

Our plugin function has access to the Nuxt app context, which has a vueApp property containing our Vue app instance. We can directly register our directives on this property and have it globally available throughout our app.

It's important to note that, to avoid issues with server-side rendering (SSR), our plugin file should not contain a .client or .server suffix when used to register directives.

That's it. Thanks for reading.

👨‍💻 Let's ConnectTwitter · GitHub · LinkedIn

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (2)

Collapse
 
poliweb profile image
Pavel Polistovskiy • Edited

Спасибо за статью. 👍

Очень полезно и позновательно про дерекивы.

Thanks for the article.

It is very useful and informative about directives.

Collapse
 
oneminch profile image
Dawit • Edited

Glad it was helpful 👍🏽

Visualizing Promises and Async/Await 🤓

async await

☝️ Check out this all-time classic DEV post on visualizing Promises and Async/Await 🤓

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay