The Power of Custom Directives in Vue
The beautiful thing about Vue is that despite the fact that it’s incredibly feature-rich. But even if you have an edge case not covered by the framework, it’s got your back there as well, because you can quite easily create a custom directive.
What are directives?
Directives are tiny commands that you can attach to DOM elements. They are prefixed with
v- to let the library know you’re using a special bit of markup and to keep syntax consistent. They are typically useful if you need low-level access to an HTML element to control a bit of behavior.
Some directives you might already be familiar with if you’ve worked with Vue (or Angular, for that matter) are
v-show, etc. We’ll go into some of the foundations, but if you’d rather read through the examples instead, you could scroll down the page a bit and probably still understand the concepts.
Here are some ways to use a directive, along with an example counterpart. These examples are not prescriptive, they’re just use-cases. The word example here is in place of the actual directive.
v-example – this will instantiate a directive, but doesn’t accept any arguments. Without passing a value, this would not be very flexible, but you could still hang some piece of functionality off of the DOM element.
v-example="value" – this will pass a value into the directive, and the directive figures out what to do based off of that value.
<div v-if="stateExample">I will show up if stateExample is true</div>
v-example="'string'" – this will let you use a string as an expression.
<p v-html="'<strong>this is an example of a string in some text</strong>'"></p>
v-example:arg="value" – this allows us to pass in an argument to the directive. In the example below, we’re binding to a class, and we’d style it with an object, stored separately.
v-example:arg.modifier="value" – this allows us to use a modifier. The example below allows us to call
preventDefault() on the click event.
Understanding Custom Directives
Now that we see all the ways we can use directives, let’s break down how we would implement them with a custom directive we author ourselves. A nice example of something you might use a custom directive for is a
scroll event, so let’s see how we’d write that.
At it’s very base, this is how we would create a global directive. (but it doesn’t do anything – yet!) – it just creates the directive.
On the element itself, it would look like:
<p v-tack>This element has a directive on ...read more
Read more here:: CssTricks