Home  >  Article  >  Web Front-end  >  Detailed explanation of Vue.js plug-in development

Detailed explanation of Vue.js plug-in development

怪我咯
怪我咯Original
2017-04-05 13:43:521418browse

Preface

As Vue.js becomes more and more popular, Vue.js related plug-ins are constantly being contributed, countless. For example, the officially recommended vue-router, vuex, etc. are all very excellent plug-ins. But more of us are still at the stage of using it and rarely develop it ourselves. So next, we will learn about the development and use of the plug-in through a simple vue-toast plug-in.

Understanding plug-ins

If you want to develop a plug-in, you must first know what a plug-in looks like.

Vue.js plug-ins should have a public method install. The first parameter of this method is the Vue constructor, and the second parameter is an optional options object:

MyPlugin.install = function (Vue, options) {
  Vue.myGlobalMethod = function () {  // 1. 添加全局方法或属性,如: vue-custom-element
    // 逻辑...
  }
  Vue.directive('my-directive', {  // 2. 添加全局资源:指令/过滤器/过渡等,如 vue-touch
    bind (el, binding, vnode, oldVnode) {
      // 逻辑...
    }
    ...
  })
  Vue.mixin({
    created: function () {  // 3. 通过全局 mixin方法添加一些组件选项,如: vuex
      // 逻辑...
    }
    ...
  })
  Vue.prototype.$myMethod = function (options) {  // 4. 添加实例方法,通过把它们添加到 Vue.prototype 上实现
    // 逻辑...
  }
}

The vue-toast plug-in to be talked about next is implemented by adding instance methods. Let's look at a small example first. First create a new js file to write the plug-in: toast.js

// toast.js
var Toast = {};
Toast.install = function (Vue, options) {
    Vue.prototype.$msg = 'Hello World';
}
module.exports = Toast;

In main.js, you need to import toast.js and use the plug-in through the global method Vue.use():

// main.js
import Vue from 'vue';
import Toast from './toast.js';
Vue.use(Toast);

Then, we get the $msg attribute defined by the plug-in in the component.

// App.vue
export default {
    mounted(){
        console.log(this.$msg);         // Hello World
    }
}

As you can see, the console successfully printed Hello World. Now that $msg can be obtained, we can implement our vue-toast plug-in.

Develop vue-toast

Requirements: Call this.$toast('Network request failed') in the component to pop up a prompt, which is displayed at the bottom by default. You can display it in different positions by calling methods such as this.$toast.top() or this.$toast.center().

To sort out my thoughts, when a prompt pops up, I can add a p in the body to display the prompt information. I can locate different positions by adding different class names, and then I can start writing.

// toast.js
var Toast = {};
Toast.install = function (Vue, options) {
    Vue.prototype.$toast = (tips) => {
        let toastTpl = Vue.extend({     // 1、创建构造器,定义好提示信息的模板
            template: &#39;<p class="vue-toast">&#39; + tips + &#39;</p>&#39;
        });
        let tpl = new toastTpl().$mount().$el;  // 2、创建实例,挂载到文档以后的地方
        document.body.appendChild(tpl);     // 3、把创建的实例添加到body中
        setTimeout(function () {        // 4、延迟2.5秒后移除该提示
            document.body.removeChild(tpl);
        }, 2500)
    }
}
module.exports = Toast;

It seems very simple, we implemented this.$toast(), and then display different positions.

<p style="margin-bottom: 7px;">// toast.js<br/>[&#39;bottom&#39;, &#39;center&#39;, &#39;top&#39;].forEach(type => {<br/>    Vue.prototype.$toast[type] = (tips) => {<br/>        return Vue.prototype.$toast(tips,type)<br/>    }<br/>})<br/></p>

Here the type is passed to $toast and processed at different positions in this method. As mentioned above, it is achieved by adding different class names (toast-bottom, toast-top, toast-center), then The $toast method needs a slight modification.

Vue.prototype.$toast = (tips,type) => {     // 添加 type 参数
    let toastTpl = Vue.extend({             // 模板添加位置类
        template: &#39;<p class="vue-toast toast-&#39;+ type +&#39;">&#39; + tips + &#39;</p>&#39;
    });
    ...
}

It seems almost done. But if I want to display it at the top by default, it seems a bit redundant that I have to call this.$toast.top() every time. Can I just put this.$toast() directly where I want it? And I don’t want it to disappear after 2.5 seconds? At this time, we noticed the options parameter in Toast.install(Vue,options). We can pass in the parameters we want through options in Vue.use(). The final modification of the plug-in is as follows:

var Toast = {};
Toast.install = function (Vue, options) {
    let opt = {
        defaultType:&#39;bottom&#39;,   // 默认显示位置
        duration:&#39;2500&#39;         // 持续时间
    }
    for(let property in options){
        opt[property] = options[property];  // 使用 options 的配置
    }
    Vue.prototype.$toast = (tips,type) => {
        if(type){
            opt.defaultType = type;         // 如果有传type,位置则设为该type
        }
        if(document.getElementsByClassName(&#39;vue-toast&#39;).length){
            // 如果toast还在,则不再执行
            return;
        }
        let toastTpl = Vue.extend({
            template: &#39;<p class="vue-toast toast-&#39;+opt.defaultType+&#39;">&#39; + tips + &#39;</p>&#39;
        });
        let tpl = new toastTpl().$mount().$el;
        document.body.appendChild(tpl);
        setTimeout(function () {
            document.body.removeChild(tpl);
        }, opt.duration)
    }
    [&#39;bottom&#39;, &#39;center&#39;, &#39;top&#39;].forEach(type => {
        Vue.prototype.$toast[type] = (tips) => {
            return Vue.prototype.$toast(tips,type)
        }
    })
}
module.exports = Toast;

In this way, a simple vue plug-in is implemented, and can be packaged and released through npm. You can use npm install to install it next time

The above is the detailed content of Detailed explanation of Vue.js plug-in development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn