用vue寫npm插件

一、調用插件

通過全局方法Vue.use()使用插件,必須在new Vue()啓動之前使用這個方法。

main.js

import cyui from 'cyui';
Vue.use(cyui);
new Vue({});

還可以傳入可選的配置對象:

Vue.use(cyui,{ someOptions:true });

那麼,平時,我們這樣調用的插件究竟是怎麼寫出來的呢?

二、開發插件

官方vue開發插件文檔傳送門

使用Vue.component()方法註冊全局組件。
第一個參數是自定義元素名稱,也就是將來在別的組件中使用這個組件的標籤名稱。
第二個參數是將要註冊的Vue組件

官方說Vue.js的插件必須有install方法**,Vue.use函數內部會調用install方法**。
如果插件沒有被註冊過,那麼註冊成功之後會給插件添加一個installed的屬性值爲true。Vue.use方法內部會檢測插件的installed屬性,從而避免重複註冊插件。

在install方法內部可以添加全局方法或者屬性、全局指令、mixin混入、添加實例方法、使用Vue.component()註冊組件等

const components = [CouponList, Coupon, UseCoupon,psbcWithdrawCoupon, UseRepayCoupon];

// 定義 install 方法,接收 Vue 作爲參數。如果使用 use 註冊插件,則所有的組件都將被註冊
const install = function(Vue) {
  // 判斷是否安裝
  if (install.installed) return;
  // 遍歷註冊全局組件
  components.map(component => Vue.component(component.name, component));
};

其他方法

const 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) {
    // 邏輯...
  }
}
三、實例

Element-ui裏面的實現:

//1.引入組件
import Popover from '../packages/popover/index.js';
import Breadcrumb from '../packages/breadcrumb/index.js';
//2.存儲組件列表
const components = [Popover,Breadcrumb]//3.寫install方法
const install = function(Vue, opts = {}) {
  locale.use(opts.locale);
  locale.i18n(opts.i18n);

  components.map(component => {
    Vue.component(component.name, component);
  });

  Vue.use(Loading.directive);

  const ELEMENT = {};
  ELEMENT.size = opts.size || '';

  Vue.prototype.$loading = Loading.service;
  Vue.prototype.$msgbox = MessageBox;
  Vue.prototype.$alert = MessageBox.alert;
  Vue.prototype.$confirm = MessageBox.confirm;
  Vue.prototype.$prompt = MessageBox.prompt;
  Vue.prototype.$notify = Notification;
  Vue.prototype.$message = Message;

  Vue.prototype.$ELEMENT = ELEMENT;
};
//4.調用install方法
/* istanbul ignore if */
if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue);
}
//5.導出對象,導出對象必須有install方法,才能被 Vue.use() 方法安裝
module.exports = {
  version: '2.3.4',
  install,
  Popover,
  Breadcrumb,
};
module.exports.default = module.exports;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章