View profile

Weekly Vue.js News - #54 - Create a custom directive

Michael Hoffmann (Mokkapps)
Michael Hoffmann (Mokkapps)
Hi ๐Ÿ‘‹
I launched the new version of my portfolio website which is based on Nuxt 3. It still has some issues as Nuxt 3 has no stable release yet.
In this issue, I will show you how you can create a custom directive in Vue and how to rethrow JavaScript errors with a cause. Additionally, you get curated articles about Vue and web development.
Have a great week โ˜€๏ธ

Vue Tip: Create a custom directive
In addition to the default set of directives like v-model or v-show, you can also register your own custom directives. For this example, letโ€™s look at how you can create a v-theme directive that applies a specific style to an element of our template.
Custom directives should be used for reusing logic that involves low-level DOM access on plain elements.
You can define the custom directive inside any Vue component:
We defined the custom directive as an object that contains the lifecycle hooks as a Vue component. The element the directive is bound to is available as the first argument of the lifecycle hooks.
In <script setup>, any camelCase variable that starts with the v prefix can be used as a custom directive.
Custom directives should only be used when the desired functionality can only be achieved via direct DOM manipulation. When possible, prefer declarative templating using built-in directives such as v-bind because they are more efficient and server-rendering friendly.
Now letโ€™s extend our directive by adding an argument that defines which theme should be applied:
At this point, you have created a custom directive that you can use in your Vue.js application.
Check the official documentation for more information.
Curated Vue Content
JavaScript Tip: Rethrow an error with cause
The cause property indicates the specific original cause of an error.
It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the the original error.
It is sometimes useful to catch an error and re-throw it with a new message. In this case you should pass the original error into the constructor for the new Error, as shown:
Curated Web Development Content
Quote of the Week
Did you enjoy this issue? Yes No
Michael Hoffmann (Mokkapps)
Michael Hoffmann (Mokkapps) @mokkapps

Hi ๐Ÿ‘‹

My name is Michael Hoffmann and I'm a Senior Frontend Developer, Freelancer and Blogger.

I focus on Vue.js, JavaScript, TypeScript and Spring Boot. Occasionally I also give career & freelancer advice.

My weekly emails reflect this preference.

In order to unsubscribe, click here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Created with Revue by Twitter.
Holzapfelkreuther StraรŸe 19, 81375 Munich, Germany