vue源碼(三)-vue組件插件開發

vue源碼(三)-vue組件插件開發

插件通常用來爲 Vue 添加全局功能。插件的功能範圍沒有嚴格的限制——一般有下面幾種:

  1. 添加全局方法或者屬性。如: vue-custom-element

  2. 添加全局資源:指令/過濾器/過渡等。如 vue-touch

  3. 通過全局混入來添加一些組件選項。如 vue-router

  4. 添加 Vue 實例方法,通過把它們添加到 Vue.prototype 上實現。

  5. 一個庫,提供自己的 API,同時提供上面提到的一個或多個功能。如 vue-router

使用插件

通過全局方法 Vue.use() 使用插件。它需要在你調用 new Vue() 啓動應用之前完成:

// 調用 `MyPlugin.install(Vue)`
Vue.use(MyPlugin)
new Vue({
  // ...組件選項
})

也可以傳入一個可選的選項對象:

Vue.use(MyPlugin, { someOption: true })

Vue.use 會自動阻止多次註冊相同插件,屆時即使多次調用也只會註冊一次該插件。

Vue.js 官方提供的一些插件 (例如 vue-router) 在檢測到 Vue 是可訪問的全局變量時會自動調用 Vue.use()。然而在像 CommonJS 這樣的模塊環境中,你應該始終顯式地調用 Vue.use()

// 用 Browserify 或 webpack 提供的 CommonJS 模塊環境時
var Vue = require('vue')
var VueRouter = require('vue-router')

// 不要忘了調用此方法
Vue.use(VueRouter)

awesome-vue 集合了大量由社區貢獻的插件和庫。

開發插件

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

MyPlugin.install = function (Vue, options) {
  // 1. 添加全局方法或屬性
  Vue.myGlobalMethod = function () {
    // 邏輯...
  }

  // 2. 添加全局資源
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // 邏輯...
    }
    ...
  })

  // 3. 注入組件選項
  Vue.mixin({
    created: function () {
      // 邏輯...
    }
    ...
  })

  // 4. 添加實例方法
  Vue.prototype.$myMethod = function (methodOptions) {
    // 邏輯...
  }
}

開發日誌記錄插件

開發一個插件,用來記錄日誌信息,能夠在生命週期中混入方法
1.創建插件Kpluginlog.js,提供可供下載安裝使用的插件,通過提供log方法,讓組件能夠使用方法進行打印日誌。其中log中需要兩個參數type, message,分別代表console中日誌打印類型,message代表需要打印的信息。

let Vue;
class PluginLog {
    constructor(option) {
        this.app  = new Vue({
            data : {
                ...option
            }
        });

        this.log = this.log.bind(this);
    }
    log(type, message) {
        const showMessage = `
        ${this.app.start}
        [${new Date()}]
        ${this.app.prefix}:${message}:${this.app.suffix}
        ${this.app.end}
        `;
        console[type](showMessage); // eslint-disable-line
    }
}
PluginLog.install = function (_Vue) {
    Vue = _Vue;
    Vue.mixin({
        beforeCreate() {
            if (this.$options.pluginLog) { // 判斷是否有添加配置,如果有的話在進行添加操作
                Vue.prototype.$pluginLog = this.$options.pluginLog;
            }
        },
        mounted() {
            if (this.$options.pluginLog) {
                this.$options.pluginLog.log('info', '加載成功...')
            }
        }
    });
};

export default PluginLog;

2.創建插件配置文件,插件中需要手動設置的一些信息,在這裏包含4個需要傳遞的參數,用於設置打印日誌時信息塊,值得注意的是Vue.use(KPluginLog);在這裏使用。

import Vue from "vue";
import KPluginLog from "./Kpluginlog";
Vue.use(KPluginLog);
export default new KPluginLog({
    start: '[-開始記錄信息-]',
    prefix: '[vue日誌記錄]',
    suffix: '[end]',
    end: '[-結束記錄信息-]',
});

3.在main.js中導入配置項,導入pluginLog配置項塊,使用插件配置內容

import Vue from "vue";
import App from "./App.vue";

import pluginLog from './pluginlog';

new Vue({
  data: {
    bar: 'bar'
  },
  pluginLog,
  render: h => h(App)
}).$mount("#app");

4.頁面中具體使用,點擊按鈕,通過 this.$pluginLog.log調用插件方法,進行打印日誌。

<script>
export default {
  name: "PluginLogCom",
  methods: {
    add() {
      this.$pluginLog.log('warn', '點擊add按鈕!!!,測試插件pluginLog');
    },
    asyncAdd() {
      this.$pluginLog.log('info', '點擊asyncAdd按鈕!!!,測試插件pluginLog');
    }
  }
};
</script>

5.點擊按鈕後效果顯示需要打印的信息:
在這裏插入圖片描述

開發Toast自定義組件

開發一個Toast插件,用來進行提示信息
1.創建插件wtoast.js,使用Vue.component進行註冊組件,其中註冊的組件原始樣式通過import wToast from './wtoast.vue'導入註冊,組件名稱使用wToast.name 組件的name屬性。

import wToast from './wtoast.vue'
let wtoast = {};
wtoast.install = function (Vue, options) {
  Vue.component(wToast.name, wToast) // wToast.name 組件的name屬性
}
export default wtoast;

2.創建wtoast.vue文件,通過template規定組件顯示佈局樣式,name提供名稱屬性,數據默認爲空,並且不顯示狀態,同時提供toastPlugin方法進行使用時調用。

<template>
  <div>
    <div class="toast"  ref='toastPosition' :class="{active: toastHidden}">
      <div class="toast-warpper">
        {{text}}
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'test-wtoast',
    data () {
      return {
        text: '',
        toastHidden: false
      }
    },
    // created () {
    //   this.toastPlugin()
    // },
    components: {
    },
    methods: {
      toastPlugin (msg, time) {
        this.text = msg
        this.toastHidden = true
        setTimeout(() => {
          this.toastHidden = false
        }, time)
      }
    }
  }
</script>

<style>
  .toast {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 0px;
    min-height: 0px;
    text-align: center;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 5px;
    color: #fff;
    transition: all 0.5s;
    z-index: -1;
    opacity: 0;
  }
  .toast.active {
    width: 150px;
    min-height: 25px;
    opacity: 1;
    z-index: 11;
  }
</style>

3.在main.js中導入並且使用

import Vue from "vue";
import App from "./App.vue";

import pluginLog from './pluginlog';
// 引入插件並使用
import WToast from './plugin/wtoast';
Vue.use(WToast);


new Vue({
  data: {
    bar: 'bar'
  },
  pluginLog,
  render: h => h(App)
}).$mount("#app");

4.頁面中具體使用,點擊按鈕,通過調用插件toastPlugin方法,進行打印日誌。

<template>
  <div class="home">
    <test-wtoast ref="wToast"></test-wtoast>
    <div @click="showMessage">點擊彈窗</div>
  </div>
</template>

<script>

export default {
  name: 'home',
  methods: {
    showMessage(){
      console.log(this.$refs.wToast);
      this.$refs.wToast.toastPlugin('調用插件toast', 5000);
    }
  }
}
</script>

5.點擊按鈕後效果顯示Toast信息:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章