Vue plugin writing and publishing npm

Introduction to vue plugin

1. Plug-ins and components

Before explaining the plug-in, let's first understand the relationship between the vue plug-in and the component. In our vue project, we often use the component more frequently than the plug-in.

 

 

 

 

Before encapsulating components, if you do not use third-party plug-ins, then in many cases we will write several commonly used components to provide for the page to use, such as Alert / Loading components, and you may need to introduce in many pages and register through components Components, but components with a high usage rate like this generally we want to be directly available on the corresponding page after global registration, so we need to encapsulate them into plug-ins, such as ui component library like vux, which provides component functions and also provides Some globally registered plugins have been added.

A simple summary of the relationship between the two is: plug-ins can encapsulate components, components can expose data to plug-ins.

 

 

 The writing methods of vue plug-ins are generally divided into 4 categories, as shown in the figure above. The main registration and binding mechanisms are as follows:

export default { 
    install (Vue, options) { 
        Vue.myGlobalMethod = function () {   // 1. Add global methods or attributes, such as: vue-custom-element
             // logic ... 
        } 

        Vue.directive ( ' my-directive ' , {   // 2. Add global resources: instructions / filters / transitions, etc., such as vue-touch 
            bind (el, binding, vnode, oldVnode) {
                 // logic ... 
            } 
            ... 
        }) 

        Vue.mixin ( { 
            created: function () {   // 3. Add some component options through the global mixin method, such as: vuex
                 // Logic ...
            } 
            ... 
        })     

        Vue.prototype. $ MyMethod = function (options) {   // 4. Add instance methods and implement them by adding them to Vue.prototype
             // logic ... 
        } 
    } 
}

The above code uses the es6 part of the syntax to list four methods for writing plug-ins, and install is the main method for registering plug-ins. It contains two parameters (Vue instance and custom configuration attribute options). We can store the above code to plugins.js.

3. Use of plugins

In plugins.js we just wrote an empty shell of the plugin. If we now need to register the plugin globally, we can register it in the entry file, such as main.js:

...

import Vue from 'vue'
import MyPlugin from './plugins/plugins.js'

Vue.use(MyPlugin);

...

The plugin can be used through the global method Vue.use (), which automatically calls the install method. Vue.use will automatically prevent registering the same plugin multiple times, at which time the plugin will only be registered once.

Vue plugin writing method

We mentioned 4 methods for writing plugins above, and then we will explain them one by one:

1. Add global methods or properties

export default {
    install(Vue, options) {
        Vue.$myName = '劳卜';
    }
}

In the install method, we directly declare the $ myName attribute on the Vue instance and assign a value. When the plugin is registered, you can get the value of Vue. $ MyName as long as there is a Vue instance, because it is directly bound to On the Vue instance.

2. Add global resources

export default { 
    install (Vue, options) { 
        Vue.directive ( ' focus ' , { 
            bind: function () {}, 

            // When the binding element is inserted into the DOM. 
            inserted: function (el, binding, vnode, oldVnode) { 

                // focus element 
                el.focus (); 
            }, 

            update: function () {}, 
            componentUpdated: function () {}, 
            unbind: function () {} 
        }); 
    }, 
}

Adding global resources includes adding global instructions / filters / transitions, etc. In the above code, we added a global instruction v-focus through Vue.directive (), which mainly contains 5 methods, where inserted represents when the binding element is inserted Go to the DOM, and el.focus () represents the focus-bound element, so if we bind this instruction to an input input box, it will automatically focus focus.

For other methods and uses provided by the directive, please refer to: vue custom instructions

3. Add global mixin method

export default {
    install(Vue, options) {
        Vue.mixin({
            methods: {
                greetingFn() {
                    console.log('greeting');
                }
            }
        });
    },
}

Mixin stands for mixing, and we can register a mix globally, which will affect every Vue instance created after registration. After the code above is registered, the greetingFn method will be added to each component instance, which can be passed directly in single-file components. greetingFn () call. Of course, if there is a method with the same name in the instance, the mixin method will be overwritten, and the hook in the mixin object will be called before the hook of the component itself.

4. Add instance method

export default {
    install(Vue, options) {
        Vue.prototype.$myName = '劳卜';
        Vue.prototype.showMyName = value => {
            console.log(value);
        };
    },
}

Adding an instance method is the most commonly used method, which is directly bound to vue's prototype chain. We can recall the concept of classes in JS. The instance method can be called inside this component through this. $ MyMethod.

5. Plug-in package components

The above 4 points only explain the 4 methods of writing the plug-in itself, and do not involve the content of the component. If we want to write the plug-in on the basis of the component, we can use Vue.extend (component). .

loading plugin

<!-- loading.vue组件 -->
<template>
    <div class="loading-box" v-show="show">
        <div class="loading-mask"></div>
        <div class="loading-content">
            <div class="animate">
            </div>
            <div class="text">{{text}}</div>
        </div>
    </div>
</ template>

<script> 
export default { 
    props: { 
        show: Boolean, 
        text: { 
          type: String, 
          default : ' Loading ... ' 
        }, 
    } 
}
 </ script>

The above is a loading.vue component, omitting the style part. Before there is no package plugin, we can only use it by importing and registering into the components object to use it on the page, such as:

<template>
    <div>
        <loading :show="true"></loading>
    </div>
</template>
<script>
import Loading from './loading.vue'

export default {
    ...

    components: {
        Loading
    }

    ...
}
</script>

Here we will encapsulate the component:

// loading.js
import LoadingComponent from '../components/loading.vue'

let $vm

export default {
    install(Vue, options) {
        if (!$vm) {
            const LoadingPlugin = Vue.extend(LoadingComponent);

            $vm = new LoadingPlugin({
                el: document.createElement('div')
            });

            document.body.appendChild($vm.$el);
        }

        $vm.show = false;

        let loading = {
            show(text) {
                $vm.show = true;

                $vm.text = text;
            },
            hide() {
                $vm.show = false;
            }
        };

        if (!Vue.$loading) {
            Vue.$loading = loading;
        }

        // Vue.prototype.$loading = Vue.$loading;

        Vue.mixin({
            created() {
                this.$loading = Vue.$loading;
            }
        })
    }
}

Above we create a new loading.js file, introduce our loading.vue component, and then create a constructor LoadingPlugin through the Vue.extend () method, and then we create a $ vm instance through new LoadingPlugin () and mount it to On a div element. Finally, we need to insert it into the DOM node through document.body.appendChild ($ vm. $ El).

When we create a $ vm instance, we can access the properties and methods of the instance. For example, through $ vm.show, we can change the show value of the loading component to control its display and hiding.

Finally, we added the $ loading event globally through Vue.mixin or Vue.prototype. $ Loading, which also contains two methods, show and hide. We can use this. $ Loading.show () to display loading directly on the page, and use this. $ Loading.hide () to turn off loading.

Plugin release

After the plug-in is written, in addition to the local reference registration, our purpose may be to publish it online for others or other projects, so we need to understand the method of plug-in publishing.

1. Release Preparation

You need an npm account before publishing the plugin, you can visit: https://www.npmjs.com/  to register

2. Issue commands

npm login 
cd directory 
npm publish

After you have an account, you need to enter the npm login command on the console to log in to your account and enter your email address. Then open your plugin directory and allow npm publish to publish. The simplest plugin directory is as follows:

3. Release directory

├── lib // Plugin source 
code│ ├── components // component directory│ 
│ └── loading.vue // component 
file│ └── index.js   // plugin entry file 
├── index.js // entrance file 
└── package.json   // package management file

You can install the loading plugin just for reference in the project. I have posted it to npm:

npm install super-loading --save

This article is from https://www.cnblogs.com/luozhihao/p/7414419.html

Guess you like

Origin www.cnblogs.com/qdlhj/p/12718357.html