我们在初学Vue时,第一个上手的例子基本都是 new Vue({el:’#app’}),但是为什么Vue实例只能挂载在一个div上呢?同样的当我们开始写第一个Vue页面的时候,我们试图在template标签下写两个div,Vue提醒我们只能写一个元素,但是为什么只能有一个元素呢?很多时候我们都已经习以为常,但是却说不上来为什么。
Vue.prototype.$mount = function ( el?: string | Element, hydrating?: boolean ): Component{ 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.` ) returnthis } //以下省略无关代码 //... }
可以看到挂载函数传了一个el参数,这个参数可以是string类型,也可以是一个element元素,也就是dom节点。最重要的是
el = el && query(el)
这一行代码,那就继续看一下query函数是做什么的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/** * Query an element selector if it's not an element already. */ exportfunctionquery (el: string | Element): Element{ if (typeof el === 'string') { const selected = document.querySelector(el) if (!selected) { process.env.NODE_ENV !== 'production' && warn( 'Cannot find element: ' + el ) returndocument.createElement('div') } return selected } else { return el } }