el我們應(yīng)該都不陌生,從我們開始學(xué)習(xí)vue開始做練習(xí)時應(yīng)該都會用到
<div id="app">
{{foo}}
</div>
<script>
const app = new Vue({
el: '#app',
data() {
return {
foo: 'hello vue'
}
}
})
</script>
但是我們真的了解他嗎?
其實vue官網(wǎng)有詳細(xì)的介紹
el
- 類型:
string | Element- 限制:只在用
new創(chuàng)建實例時生效。- 詳細(xì):
(注意)提供一個在頁面上已存在的 DOM 元素作為 Vue 實例的掛載目標(biāo)。可以是 CSS 選擇器,也可以是一個 HTMLElement 實例。
在實例掛載之后,元素可以用vm.$el訪問。
如果在實例化時存在這個選項,實例將立即進(jìn)入編譯過程,否則,需要顯式調(diào)用vm.$mount()手動開啟編譯。
提供的元素只能作為掛載點。不同于 Vue 1.x,所有的掛載元素會被 Vue 生>成的 DOM 替換。因此不推薦掛載 root 實例到<html>或者<body>上。
如果render函數(shù)和templateproperty 都不存在,掛載 DOM 元素的 HTML 會被提取出來用作模板,此時,必須使用 Runtime + Compiler 構(gòu)建的 Vue 庫。
如上所述:el可以是一個字符串,也可以是一個dom
<div>{{foo}}</div>
<script>
/*
el: string | Element
*/
const app = new Vue({
el: document.querySelector('div'),
// el: '#app',
data() {
return {
foo: 'dsads'
}
}
})
</script>
從源碼中可以找到答案
/*src/platforms/web/entry-runtime-with-compiler.js*/
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
/*query*/
el = el && query(el)
/* istanbul ignore if */
if (el === document.body || el === document.documentElement) {
process.env.NODE_ENV !== 'production' && warn(
`Do not mount Vue to <html> or <body> - mount to normal elements instead.`
)
return this
}
/*src/platforms/web/util/index.js*/
export function query (el: string | Element): Element {
if (typeof el === 'string') {
// 如果是string 則獲取dom元素
const selected = document.querySelector(el)
if (!selected) {
process.env.NODE_ENV !== 'production' && warn(
'Cannot find element: ' + el
)
return document.createElement('div')
}
return selected
} else {
// 否則 直接使用
return el
}
}