Plug-in development

Most plug-ins of VUE add global functions to vUE. The methods to add global functions are as follows:

  1. Add global methods or attributes:
Vue.uiname = 'star-ui-vue'

// In the project, you can get the value of uiname with vue. uiname
Copy the code
  1. Add global resources: directives/filters/transitions
  2. Through the globalmixinMethod to add some component options
  3. addvueInstance method. By adding them tovue.prototypeImplementation we are usingscriptThe introduction ofvue“Usually firstnewavueThis is becausevueAs an object itself, it provides us with images$setSuch a global method, so in makingvueWhen plugins, we can copy this way, givevueprototypeAdd global properties or methods.
  4. Implement a library by providing implementations of one or more of the above plug-ins.

The plug-in package

Plug-ins for Vue should have a public install method. The first argument to this method is a Vue constructor, and the second argument is an optional object.

const MyPlugin = {
    install (Vue,options) {
        // 1. Add global properties or methods
        Vue.pluginName = 'MyPlugin'
        Vue.pluginMethods = (a)= > {
            console.log('self methods')}//2. Add global resources
        Vue.directive('my-directive',{ bind(el,binding,vnode){... } }) Vue.filter('my-filter',(val) => '$' + val)

        // global mixin injection
        Vue.mixin({
            created(){
                console.log('mixin')
            },
            data(){
                return {
                    initData: 'init data'}}})// 4. Add instance methods or attributes
        Vue.prototype.$myMethod = (option) = > {
            console.log('my method')}}}Copy the code

The use of plug-in

Use the plug-in with the global method vue.use ()

// main.js
import Vue from 'Vue'
import MyPlugin from 'myPlugin'

Vue.use(MyPlugin)

// 1. View global properties or call global methods
console.log(Vue.pluginName)   // 'MyPlugin'
Vue.pluginMethods()    // 'self methods'.Copy the code
// App.vue

// 2. Invoke global resources
<button my-directive></button>	

// 3. Data or methods defined during global mixin injection will be merged in all VUE components

// 4. Add instance methods or attributes

methods:{
    test(){
        this.$myMethod()   // 'my method'}}Copy the code

Many times to register

Vue.use automatically prevents multiple registrations of the same plug-in and only registers the plug-in once.

implementation


export function initUse(Vue:GlobalAPI){
    Vue.use function (plugin: Function | object) {
        // Create a component if it does not already exist
        const installedPlugins = (this._initlledPlugins || this.installedPlugins = [])

        // Check whether the component is created and return if it is
        if(installedPlugins.indexOf(plugin) > - 1) {
            return this}... }}Copy the code