1. 程式人生 > >Vue.js 插件開發詳解

Vue.js 插件開發詳解

js

前言

隨著 Vue.js 越來越火,Vue.js 的相關插件也在不斷的被貢獻出來,數不勝數。比如官方推薦的 vue-router、vuex 等,都是非常優秀的插件。但是我們更多的人還只停留在使用的階段,比較少自己開發。所以接下來會通過一個簡單的 vue-toast 插件,來了解掌握插件的開發和使用。

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

認識插件

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

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

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.js

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

在 main.js 中,需要導入 toast.js 並且通過全局方法 Vue.use() 來使用插件:

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

然後,我們在組件中來獲取該插件定義的 $msg 屬性。

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

可以看到,控制臺成功的打印出了 Hello World 。既然 $msg 能獲取到,那麽我們就可以來實現我們的 vue-toast 插件了。

開發 vue-toast

需求:在組件中通過調用 this.$toast(‘網絡請求失敗‘) 來彈出提示,默認在底部顯示。可以通過調用 this.$toast.top() 或 this.$toast.center() 等方法來實現在不同位置顯示。

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

// toast.jsvar Toast = {};Toast.install = function (Vue, options) {
    Vue.prototype.$toast = (tips) => {
        let toastTpl = Vue.extend({     // 1、創建構造器,定義好提示信息的模板
            template: ‘<div class="vue-toast">‘ + tips + ‘</div>‘
        });
        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;

好像很簡單,我們就實現了 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.js 插件開發詳解