由於有看到索尼大佬的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
。