由于有看到索尼大佬的element源码阅读博客,怀着敬仰的心情拜读发现本身是个菜鸟,发现本身的知识是真的很薄弱😭,因此决心本身手动起来,边实现源码边读边记录。 我会将本身实践过程当中的部分问题也放在文章中,但愿大佬们能帮帮我这个菜鸟,拜谢。css
模仿代码中均以el-test 替换el, 目的是为了边模仿边测试和el组件的效果对比vue
这是项目的主体结构 node
提出疑问一webpack
为何element的文件会这样放置? 对我这个菜鸟而言,我以为把css和vue放在同一个组件下不是更加的方便,尤为是在有如此多的组件,若是element的开发人员想要更改某些样式,那不是还要去lib下找很久?es6
/plugins/index.js 仿照element的index文件,导入全部的组件 index.js的代码如今以下web
import ElTestRow from "./el-test-row/row.js"
import ElTestCol from "./el-test-col/col.js"
const components = [ElTestRow, ElTestCol]
export default function install(Vue){
//注册组件
components.forEach(component => {
console.log(component)
Vue.component(component.name, component)
})
}
if(typeof window !== undefined && window.Vue) {
console.log('using install')
}
复制代码
和element的index有区别的地方在于 咱们使用element的时候咱们在main.js中须要element-ui
import ElementUI from 'element-ui';
Vue.use(ElementUI);
复制代码
个人实现须要以下方法引入bash
import install from '@/plugins/index.js'
install(Vue)
复制代码
缘由是由于在element的index中install方法以下函数
const install = function(Vue, opts = {}) {
locale.use(opts.locale);
locale.i18n(opts.i18n);
components.forEach(component => {
Vue.component(component.name, component);
});
};
/* istanbul ignore if */
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue);
}
复制代码
按照个人理解,element中是检测了window.Vue是否存在,而后执行install方法,导入全部组件,可是在仿制过程当中,我发现个人代码并无执行install方法,个人index中学习
if(typeof window !== undefined && window.Vue) {
console.log('using install')
}
复制代码
并无执行打印操做,因此须要在main中执行install方法
提出疑问二 (已解决于2919-06-29,答案见文章尾)
有没有大佬能够告诉我这是由于什么缘由,个人console.log并无执行, element是怎么执行了install方法?
本篇算是开篇,之后会陆续更新,我会把本身学习的心得和疑惑都放出来,若是有解决方案我也会在后续的文章中说明。但愿和你们一块儿学习。
Vue源码中对于Vue.use有过描述,Vue.use(xxx)会检测xxx中是否包含install方法,并执行。所以,plugins/inddex.js文件修改以下
const install = function (Vue){
//注册组件
components.forEach(component => {
console.log(component)
Vue.component(component.name, component)
})
}
export default {
install
}
复制代码
在main.js中
import ElTestUI from '@/plugins/index.js'
// 导入组件
Vue.use(ElTestUI);
复制代码
(如下内容来自一位头条大佬的解释)
而且 console.log
未打印的缘由并非if
未执行,在import
的时候,if
函数已经执行,可是由于使用了webpack
而且是在nodes
环境下运行的vue
项目,node
环境下并没有window
变量,所以不会执行。 if
的本意是为了判断element
库的使用是经过cdn
方式仍是经过es6
语法编译而成,经过cdn
引入的状况为了保证代码可以正常使用vue
,须要暴露给window
一个vue
变量,此时if
值为true
,将执行if
里的console
。