7

How To Create Custom Vue.js Plugins

 3 years ago
source link: https://www.digitalocean.com/community/tutorials/vuejs-creating-custom-plugins
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Introduction

Vue.js plugins are a powerful but simple way to add global features to your app. They have a variety of uses, from distributing app-wide components to adding additional capabilities such as routing and immutable data stores to your app.

In this article, you will build an example Vue custom plugin.

Prerequisites

To follow along with this article, you will need:

This tutorial was verified with Node v16.5.0, npm v6.14.8, and vue v2.6.11.

Building Your First Plugin

As an introduction to the world of Vue plugins, we’re going to write a plugin that writes to the console every time a component is mounted to the DOM.

my-vue-plugin.js
const MyPlugin = {
  // eslint-disable-next-line no-unused-vars
  install(Vue, options) {
    Vue.mixin({
      mounted() {
        console.log('Mounted!');
      }
    });
  }
};

export default MyPlugin;
 

A Vue plugin is an object with an install method that takes two parameters:

  • the global Vue object
  • and an object containing user-defined options

Vue.mixin() is used to inject functionality into all components. In this case, the mounted() method runs when the component is added to the DOM.

Your plugin can now be used in a Vue app by importing it and calling Vue.use(MyPlugin):

main.js
import Vue from 'vue'
import MyPlugin from './my-vue-plugin.js'
import App from './App.vue'

Vue.use(MyPlugin)

new Vue({
  el: '#app',
  render: h => h(App)
});
 

You might be wondering, why couldn’t I just do this by calling Vue.mixin() in main.js? The reason is that since we’re adding global functionality to Vue that does not modify the app directly, it’s almost always best to split that out into a separate module that can be added or removed at will. It also makes plugins incredibly easy to distribute.

Adding Capabilities

Adding Component Lifecycle Hooks or Properties

As depicted above in the “Your First Plugin” example, you can add lifecycle hooks and make other modifications to Vue components by using a Mixin.

Note: Mixins are a fairly advanced topic that is outside the scope of this article. For now, a sufficient explanation is that they’re essentially component definitions that get combined into (“mixed in”) other components.

my-vue-plugin.js
const MyPlugin = {
  // eslint-disable-next-line no-unused-vars
  install(Vue, options) {
    Vue.mixin({
      mounted() {
        console.log('Mounted!');
      }
    });
  }
};

export default MyPlugin;
 

Installing App-Wide Components and Directives

If you wish to package components or directives to be distributed as a plugin, you might write something like this:

my-vue-plugin.js
import MyComponent from './components/MyComponent.vue'
import MyDirective from './directives/MyDirective.js'

const MyPlugin {
  // eslint-disable-next-line no-unused-vars
  install(Vue, options) {
    Vue.component(MyComponent.name, MyComponent)
    Vue.directive(MyDirective.name, MyDirective)
  }
};

export default MyPlugin;
 

Modifying the Global Vue Object

You can modify the global Vue object from a plugin:

my-vue-plugin.js
const MyPlugin {
  // eslint-disable-next-line no-unused-vars
  install(Vue, options) {
    Vue.myAddedMethod = function() {
      return Vue.myAddedProperty
    }
  }
};

export default MyPlugin;
 

Modifying Vue Instances

To add a property or method directly to component instances without any injection mechanism, you can modify the Vue prototype as shown here:

my-vue-plugin.js
const MyPlugin {
  // eslint-disable-next-line no-unused-vars
  install(Vue, options) {
    Vue.prototype.$myAddedProperty = 'Example Property'
    Vue.prototype.$myAddedMethod = function() {
      return this.$myAddedProperty
    }
  }
};

export default MyPlugin;
 

Those properties will now be added to all components and Vue instances.

Note: Within the Vue community, it is generally expected that plugins that modify the Vue prototype prefix any added properties with a dollar sign ($).

Supporting Automatic Installation

For people who use your plugin outside of a module system, it is often expected that if your plugin is included after the Vue script tag, that it will automatically install itself without the need to call Vue.use(). You can implement this by appending these lines to the end of my-vue-plugin.js:

if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(MyPlugin)
}
 

Automatic installation if Vue has been added to the global scope.

Distributing Your Plugin

Once you’ve written a plugin, you can distribute it to the community. If you’re not already familiar with the process, here are some common steps for helping people discover your plugin:

  1. Publish the source code and distributable files to npm and GitHub. Make sure you choose a fitting license for your code!
  2. Open a pull request to the official Vue cool-stuff-discovery repository: awesome-vue. Lots of people come here to look for plugins.
  3. (Optional) Post about it on the Vue Forum, Vue Gitter Channel and on Twitter with the hashtag #vuejs.

Go make some plugins!

Conclusion

In this article, you built an example Vue custom plugin.

Continue your learning with Vue documentation for Plugins and Mixins.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK