What is Vue.JS Custom Directive and How to Create It

What is Vue.JS Custom Directive and How to Create It

What is Vue.js Custom Directive and How to Create It

Directives are code snippets that allow selected (DOM) or components or elements inserted to act according to their definition, written with the syntax rule v-directiveName (syntax). There are certain built-in directives within Vue.js. With these predefined capable directives, various processes are carried out much more practically. Let's say these directives do not meet our needs, so what will we do? There is also a practical solution to that with Vue.js Custom Directive.

If the directives provided by Vue.js are insufficient or do not meet our requirements, Vue.js allows us to create our own directives. These are called custom directives. Let's explore together how to create a custom directive in Vue.js.

When creating any custom directive, we need to define this directive globally in main.js to call and use it everywhere. The definition looks like this:

Description

Five different methods are needed for the directive to function, and these are called Directive Hooks. Directive Hooks are methods that are triggered in the lifecycle of the directive, and the most commonly used one is the bind (el, binding) method seen in the example above, which holds some parameters; now let's take a look at the parameters that this method takes.

el: This parameter allows us to access the element where the directive is used. (intervention to the DOM)
binding: This parameter holds and shows us which argument the specified directive takes and what type of data is being sent. (properties)

How Can We Send Data to the Directive We Created?

We may want to send any data to the directive that we defined in main.js within our app.vue file; after all, we would not want to use a directive that only has a single value constantly. So, how will we do this?

Description

How Will We Use It?

The answer is very simple. There is no difference from the directives normally used. You can examine below...

Description

Result

Description

Thank you for reading, see you in our next blog with new information.

We will be sharing a great application next week, stay tuned