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 is how you declare a new directive. The bind hook is called when the directive is


bound to the element. The only thing we are doing now is setting the background color. We


also want to make it change color after each click. To do this, you have to add this code:


Vue.directive('pony', {
bind (el) {
el.style.backgroundColor = 'hotpink'
el.onclick = () => {
const colGen = () =>
Math.round(Math.random()*255 + 25)
const cols =
[colGen() + 100, colGen(), colGen()]
const randRGB =
`rgb(${cols[0]}, ${cols[1]}, ${cols[2]})`
el.style.backgroundColor = randRGB
}
}
})

Here, we are creating an onclick listener that will generate a random color with a bias


toward red and assign it as a new background color.


At the end of our JavaScript, remember to create a Vue instance:


new Vue({
el: '#app'
})

You can launch your application to see your directive in action:


Don't forget to click on the text to change the background color!

Free download pdf