Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Advanced Vue.js - Directives, Plugins, and Render Functions Chapter 17

This chapter is for the slightly more experienced, and you probably won't find the level of


step-by-step detail found in other recipes, but I have strived to make them complete
nonetheless.


Creating a new directive


Directives are like mini functions that you can use to quickly drop into your code, mainly to
improve the user experience, and to add new low-level features to your graphic interface.


Getting ready


This recipe, although found in the advanced chapter, is really easy to complete. The main


reason directives are advanced is because you should usually prefer composition to add


functionality and style to your apps. When components won't cut it, use directives.


How to do it...


We will build a v-pony directive that will turn any element into a pony element. A pony


element is created with a pink background and changes color when you click on it.


The HTML code for the pony element is as follows:


<div id="app">
<p v-pony>I'm a pony paragraph!</p>
<code v-pony>Pony code</code>
<blockquote>Normal quote</blockquote>
<blockquote v-pony>I'm a pony quote</blockquote>
</div>

Just to show the difference, I've included a normal blockquote element. In our JavaScript


section, write the following:


Vue.directive('pony', {
bind (el) {
el.style.backgroundColor = 'hotpink'
}
})
Free download pdf