ShiningDan的博客

一天一个 Element 组件 - 简单介绍入口文件

本文是 Element 的组件源码学习系列。

项目源码:ElemeFE/element | GitHub,Tag:v2.13.0

一般我们在看一个项目,首先要看的是这个项目的目录结构和 package.json

项目结构中:

  1. .github 存放的是如何提 PR、Issus、贡献代码的流程
  2. build 里面放的是打包构建的脚本
  3. examples 里面放的是组件示例
  4. packages 里面是组件源码
  5. src 放的是入口文件,还有一些其他辅助文件
  6. test 里面是单测文件
  7. types 是类型定义文件
  8. components.json 配置文件里面列出了组件目录,以及对应源码的位置,应该是给 webpack 打包的时候使用的

入口文件

来看一下入口文件 src/index.js 吧。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import Pagination from '../packages/pagination/index.js';
import Dialog from '../packages/dialog/index.js';
...
// 引入所有的组件

import locale from 'element-ui/src/locale';
import CollapseTransition from 'element-ui/src/transitions/collapse-transition';

// 定义所有组件列表数组
const components = [
Pagination,
Dialog,
...
]

const install = function(Vue, opts = {}) {
// 国际化的配置初始化
locale.use(opts.locale);
locale.i18n(opts.i18n);

// 将所有的组件注册成全局组件
components.forEach(component => {
Vue.component(component.name, component);
});

// 全局注册指令
Vue.use(InfiniteScroll);
Vue.use(Loading.directive);

// 设置全局尺寸,某些组件,如 button,没有设置尺寸时,会继承全局尺寸
Vue.prototype.$ELEMENT = {
size: opts.size || '',
zIndex: opts.zIndex || 2000
};

// 在 Vue 原型上挂载一些简易的方法
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;

};

前面定义的是 Element 的 install 方法。因为 Element 是基于 Vue 的组件库,所以在调用 install 方法的时候,要判断 Vue 对象已经被挂载到了 window 上:

1
2
3
4
/* istanbul ignore if */
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue);
}