Vue.js 插件開發詳解

前言

隨着 Vue.js 愈來愈火,Vue.js 的相關插件也在不斷的被貢獻出來,數不勝數。好比官方推薦的 vue-router、vuex 等,都是很是優秀的插件。可是咱們更多的人還只停留在使用的階段,比較少本身開發。因此接下來會經過一個簡單的 vue-toast 插件,來了解掌握插件的開發和使用。javascript

原文做者:林鑫,做者博客:https://github.com/lin-xin/blogvue

認識插件

想要開發插件,先要認識一個插件是什麼樣子的。java

Vue.js 的插件應當有一個公開方法 install 。這個方法的第一個參數是 Vue 構造器 , 第二個參數是一個可選的選項對象:node

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 上實現
    // 邏輯...
  }
}

接下來要講到的 vue-toast 插件則是經過添加實例方法實現的。咱們先來看個小例子。先新建個js文件來編寫插件:toast.jsgit

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

在 main.js 中,須要導入 toast.js 而且經過全局方法 Vue.use() 來使用插件:github

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

而後,咱們在組件中來獲取該插件定義的 $msg 屬性。vue-router

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

能夠看到,控制檯成功的打印出了 Hello World 。既然 $msg 能獲取到,那麼咱們就能夠來實現咱們的 vue-toast 插件了。vuex

開發 vue-toast

需求:在組件中經過調用 this.$toast('網絡請求失敗') 來彈出提示,默認在底部顯示。能夠經過調用 this.$toast.top() 或 this.$toast.center() 等方法來實如今不一樣位置顯示。npm

整理一下思路,彈出提示的時候,我能夠在 body 中添加一個 div 用來顯示提示信息,不一樣的位置我經過添加不一樣的類名來定位,那就能夠開始寫了。網絡

// toast.js
var Toast = {};
Toast.install = function (Vue, options) {
    Vue.prototype.$toast = (tips) => {
        let toastTpl = Vue.extend({     // 一、建立構造器,定義好提示信息的模板
            template: '<div class="vue-toast">' + tips + '</div>'
        });
        let tpl = new toastTpl().$mount().$el;  // 二、建立實例,掛載到文檔之後的地方
        document.body.appendChild(tpl);     // 三、把建立的實例添加到body中
        setTimeout(function () {        // 四、延遲2.5秒後移除該提示
            document.body.removeChild(tpl);
        }, 2500)
    }
}
module.exports = Toast;

好像很簡單,咱們就實現了 this.$toast() ,接下來顯示不一樣位置。

// toast.js
['bottom', 'center', 'top'].forEach(type => {
    Vue.prototype.$toast[type] = (tips) => {
        return Vue.prototype.$toast(tips,type)
    }
})

這裏把 type 傳給 $toast 在該方法裏進行不一樣位置的處理,上面說了經過添加不一樣的類名(toast-bottom、toast-top、toast-center)來實現,那 $toast 方法須要小小修改一下。

Vue.prototype.$toast = (tips,type) => {     // 添加 type 參數
    let toastTpl = Vue.extend({             // 模板添加位置類
        template: '<div class="vue-toast toast-'+ type +'">' + tips + '</div>'
    });
    ...
}

好像差很少了。可是若是我想默認在頂部顯示,我每次都要調用 this.$toast.top() 好像就有點多餘了,我能不能 this.$toast() 就直接在我想要的地方呢?還有我不想要 2.5s 後才消失呢?這時候注意到 Toast.install(Vue,options) 裏的 options 參數,咱們能夠在 Vue.use() 經過 options 傳進咱們想要的參數。最後修改插件以下:

var Toast = {};
Toast.install = function (Vue, options) {
    let opt = {
        defaultType:'bottom',   // 默認顯示位置
        duration:'2500'         // 持續時間
    }
    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('vue-toast').length){
            // 若是toast還在,則再也不執行
            return;
        }
        let toastTpl = Vue.extend({
            template: '<div class="vue-toast toast-'+opt.defaultType+'">' + tips + '</div>'
        });
        let tpl = new toastTpl().$mount().$el;
        document.body.appendChild(tpl);
        setTimeout(function () {
            document.body.removeChild(tpl);
        }, opt.duration)
    }
    ['bottom', 'center', 'top'].forEach(type => {
        Vue.prototype.$toast[type] = (tips) => {
            return Vue.prototype.$toast(tips,type)
        }
    })
}
module.exports = Toast;

這樣子一個簡單的 vue 插件就實現了,而且能夠經過 npm 打包發佈,下次就可使用 npm install 來安裝了。

演示地址:vue-toast

源碼地址:vue-toast

更多文章:blog

相關文章
相關標籤/搜索