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) {
    // 逻辑...
  }
}

iview 源码探究

import '各种组件' 
const components = {
    '各种组件'
}
const iview = {
    ...components,
    iCol: Col  // 对于特殊的以i开头的,再赋值一次
}

const install = function(Vue, opts = {}) { // 定义install 函数
    if (install.installed) return;  // 防止多次注册
    locale.use(opts.locale);
    locale.i18n(opts.i18n);

    Object.keys(iview).forEach(key => { // 注册全局组件
        Vue.component(key, iview[key]);
    });

    Vue.prototype.$Loading = LoadingBar;
    Vue.prototype.$Message = Message;
    Vue.prototype.$Modal = Modal;
    Vue.prototype.$Notice = Notice;
    Vue.prototype.$Spin = Spin;
};

// auto install
if (typeof window !== 'undefined' && window.Vue) {
    install(window.Vue);
}

const API = {
    version: process.env.VERSION, // eslint-disable-line no-undef
    locale: locale.use,
    i18n: locale.i18n,
    install,
    Circle,             // todo 这些为什么还要再搞一次
    Switch,
    ...components
};

API.lang = (code) => {
    const langObject = window['iview/locale'].default;
    if (code === langObject.i.locale) locale.use(langObject);
    else console.log(`The ${code} language pack is not loaded.`); // eslint-disable-line no-console
};

module.exports.default = module.exports = API;   // eslint-disable-line no-undef

思考

插件可以分为几大类:

  1. 组件
  2. 过滤器/指令
  3. 全局方法、属性
  4. 实例方法、属性
  5. 通过mixin 注入组件(需要详纠)

知道了这些,对于iview的整体构思也就清楚了,那么需要知道每个组件的实现,深入到组件内部就好。同时关于grid这个需要详细研究下,另外对于iview这个框架源码如何做测试也可以学习下。

展望

如果经常使用这个,以这个为基础扩展组件库,可以修改它的样式库。

做成可视化,方便以后快速写代码。

results matching ""

    No results matching ""