Advanced Vue.js - Directives, Plugins, and Render Functions Chapter 17
The atRandomIntervals function takes the specified function and calls it at random
intervals shorter than 6 seconds.
We now have all the functions we need to actually build a plugin that will make our
element jump:
const Kangaroo = {
install (vueInstance) {
vueInstance.kangaroos = []
vueInstance.directive('kangaroo', {
bind (el) {
vueInstance.kangaroos.push(el)
}
})
atRandomIntervals(() =>
doOnRandomElement(jump, vueInstance.kangaroos))
}
}
The Kangaroo plugin, when installed, creates an empty array; it declares a new
directive, kangaroo which will register all the elements with it inside the array.
Then at random intervals, one random element is drawn from the array and the jump
function is called on it.
To activate the plugin, we need one line before declaring the Vue instance (but after
declaring Kangaroo):
Vue.use(Kangaroo)
new Vue({
el: '#app'
})
We have to choose the elements that jump, that is, everything except the title:
<div id="app">
<h1>Welcome to the Kangaroo club</h1>
<img v-kangaroo src="https://goo.gl/FVDU1I" width="300px"
height="200px">
<img v-kangaroo src="https://goo.gl/U1Hvez" width="300px"
height="200px">
<img v-kangaroo src="https://goo.gl/YxggEB" width="300px"
height="200px">
<p v-kangaroo>We love kangaroos</p>
</div>