6

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

 2 years ago
source link: https://shiningdan.github.io/2020/01/01/%E4%B8%80%E5%A4%A9%E4%B8%80%E4%B8%AA-Element-%E7%BB%84%E4%BB%B6-%E9%A1%B9%E7%9B%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E5%85%A5%E5%8F%A3%E6%96%87%E4%BB%B6/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

发表于 2020-01-01

| 分类于 coding

|

| 阅读次数

本文是 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 吧。

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 上:

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK