以 Dialog 为例简单理一下 element-ui 的组件注册流程

72 阅读1分钟

element-ui 组件注册流程

首先看看 element-ui 用法

  • 引入整个 Element
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI)
  • 引入部分组件
import Vue from 'vue'
import { Dialog } from 'element-ui'

Vue.use(Dialog)

Vue.use( plugin )

  • 参数

    • {Object | Function} plugin
  • 用法

    安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入。

    该方法需要在调用 new Vue() 之前被调用。

    当 install 方法被同一个插件多次调用,插件将只会被安装一次。

由此可知,Vue.js 的插件应该暴露一个 install 方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象

Dialog 组件是如何注册的

src/index.js

import Dialog from '../packages/dialog/index.js'
...
const components = [
  ...
  Dialog,
  ...
]

const install = function(Vue, opts = {}) {
  ...
  components.forEach(component => {
    Vue.component(component.name, component);
  });
  ...
};

export default {
  ...
  install,
  Dialog,
  ...
}

packages/dialog/index.js

import ElDialog from './src/component';

ElDialog.install = function(Vue) {
  Vue.component(ElDialog.name, ElDialog);
};

export default ElDialog;

引入整个 Element 时,暴露的 install 方法会注册所有组件,如果单独引入 Dialog,则会调用 Dialog 自己的 install 方法。