Plugins

Plugins are a great way to provide extensibility to the Vue.js framework. As a matter of fact, Vuex and Vue Router, the two most widely-used core libraries in the Vue.js ecosystem, are plugins. And the validation framework that we will use in the TaskAgile app, Vuelidate, is also a Vue.js plugin.

Creating a plugin in Vue.js is simple. You create a plain object with an install() method. This method will take two arguments. The first one is the Vue constructor, which is where all of the extended functionalities will be applied, and the second one is an options object, which allows a plugin to define options that can be used to configure the plugin itself.

Inside the install() method, you can add a static method or property to the Vue constructor. You can also create custom directives, filters, components, and mixins. And you can add instance methods to Vue.prototype as well.

You might have noticed that, in our previous section, in order to use the life cycle mixin, we need to import it first. And if we want to disable it in several components, we will need to change multiple files, which is not ideal. Let's use a plugin to track instances' life cycles instead. This plugin will provide switches so that you can turn off the hooks you're no longer interested in.

Let's call this plugin lifecycle-logger. And, by convention, we will add it to the plugins directory and name the file in this format: ${pluginName}.plugin.js.

Let's have a look at the plugins/lifecycle-logger.plugin.js file:

const switchers = {
created: true,
beforeMount: true,
mounted: true,
destroyed: true
}
export default {
install (Vue, options) {
Object.assign(switchers, options)

Vue.mixin({
created () {
if (switchers.created) {
console.log(`${this.$options.name} created`)
}
},
beforeMount () {
if (switchers.beforeMount) {
console.log(`${this.$options.name} about to mount`)
}
},
mounted () {
if (switchers.mounted) {
console.log(`${this.$options.name} mounted`)
}
},
destroyed () {
if (switchers.destroyed) {
console.log(`${this.$options.name} destroyed`)
}
}
})
}
}

We use the Object.assign() method to merge switchers in the options object into predefined switchers. And we apply the life cycle hook functions as a global mixin.

To use a plugin in a Vue application, all you need to do is to import it and call Vue.use().

To use our lifecycle-logger plugin, we need to remove the lifecycle-logger mixin first. Once that is done, update index.html as follows:

 <script type="module">
...
import LifecycleLogger from './plugins/lifecycle-logger.plugin.js'
import './directives/focus.directive.js'
...
Vue.use(LifecycleLogger, {beforeMount: false})
...
</script>

As you can see, we disable the beforeMount hook tracking by using an options object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.122.68