nuxt 3 directive

Nuxt 3 Directive

As a developer, I was recently introduced to the Nuxt 3 framework and its amazing features. One of the features that caught my attention was the directive that comes with it. In simple terms, a directive is a special type of attribute that we can use to apply behaviors to elements in our HTML code. With Nuxt 3, we can create custom directives that can be used throughout our application.

Creating a Nuxt 3 Directive

To create a Nuxt 3 directive, we first need to create a new file in our project's /directives directory. We can call this file exampleDirective.js. In this file, we create a new directive using the app.directive() method that comes with Nuxt 3.


// /directives/exampleDirective.js

export default function (app) {
  app.directive('example', {
    mounted(el, binding) {
      el.innerHTML = binding.value.toUpperCase()
    }
  })
}

In this example, we're creating a new directive called example. This directive will simply take the text content of an element and convert it to uppercase.

Using a Nuxt 3 Directive

Once we've created our directive, we can use it in our HTML code by adding the v-example attribute to an element. The value of this attribute will be passed to the directive as an argument.


<div v-example="hello world"></div>

In this example, the text content of the <div> element will be converted to uppercase by our example directive. The resulting HTML code will be:


<div>HELLO WORLD</div>

Alternate Approach

Another approach to create a directive is to use the Vue.directive() method. We can create a new file named exampleDirective.js in the /directives directory and write our code as follows:


// /directives/exampleDirective.js

export default {
  mounted(el, binding) {
    el.innerHTML = binding.value.toUpperCase()
  }
}

To use this directive in our HTML code, we must import it first and then register the directive globally using Vue.directive() method.


// /plugins/exampleDirective.js

import Vue from 'vue'
import exampleDirective from '@/directives/exampleDirective'

Vue.directive('example', exampleDirective)

The above code will register the exampleDirective globally and we can now use it throughout our application by adding the v-example attribute to an element.

Conclusion

Nuxt 3 directive is a powerful tool that allows us to create custom behaviors for elements in our HTML code. By following the above steps, we can easily create and use custom directives in our Nuxt 3 application.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe