Vue 是通過(guò)?$mount?實(shí)例方法去掛載?vm?的,$mount?方法在多個(gè)文件中都有定義,如?src/platform/web/entry-runtime-with-compiler.js、src/platform/web/runtime/index.js、src/platform/weex/runtime/index.js。因?yàn)?$mount?這個(gè)方法的實(shí)現(xiàn)是和平臺(tái)、構(gòu)建方式都相關(guān)的。接下來(lái)我們重點(diǎn)分析帶?compiler?版本的?$monut?實(shí)現(xiàn)
?src/platform/web/entry-runtime-with-compiler.js?文件中定義:
const mount = Vue.prototype.$mount
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 or - mount to normal elements instead.`
??? )
??? return this
? }
? const options = this.$options
? // resolve template/el and convert to render function
? if (!options.render) {
??? let template = options.template
??? if (template) {
????? if (typeof template === 'string') {
??????? if (template.charAt(0) === '#') {
????????? template = idToTemplate(template)
????????? /* istanbul ignore if */
????????? if (process.env.NODE_ENV !== 'production' && !template) {
??????????? warn(
?????? ???????`Template element not found or is empty: ${options.template}`,
????????????? this
??????????? )
????????? }
??????? }
????? } else if (template.nodeType) {
??????? template = template.innerHTML
????? } else {
??????? if (process.env.NODE_ENV !== 'production') {
????????? warn('invalid template option:' + template, this)
??????? }
??????? return this
????? }
??? } else if (el) {
????? template = getOuterHTML(el)
??? }
??? if (template) {
????? /* istanbul ignore if */
????? if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
??????? mark('compile')
????? }
????? const { render, staticRenderFns } = compileToFunctions(template, {
??????? shouldDecodeNewlines,
??????? shouldDecodeNewlinesForHref,
??????? delimiters: options.delimiters,
??????? comments: options.comments
????? }, this)
????? options.render = render
????? options.staticRenderFns = staticRenderFns
????? /* istanbul ignore if */
????? if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
??????? mark('compile end')
??????? measure(`vue ${this._name} compile`, 'compile', 'compile end')
????? }
??? }
? }
? return mount.call(this, el, hydrating)
}
首先,$mount?方法對(duì)?el?做了限制,Vue 不能掛載在?body、html?這樣的根節(jié)點(diǎn)上。 如果沒(méi)有定義?render?方法,則會(huì)把?el?或者?template?字符串轉(zhuǎn)換成?render?方法。這里我們要牢記,在 Vue 2.0 版本中,所有 Vue 的組件的渲染最終都需要?render?方法,無(wú)論我們是用單文件 .vue 方式開(kāi)發(fā)組件,還是寫(xiě)了?el?或者?template?屬性,最終都會(huì)轉(zhuǎn)換成?render?方法,那么這個(gè)過(guò)程是 Vue 的一個(gè)“在線(xiàn)編譯”的過(guò)程,它是調(diào)用?compileToFunctions?方法實(shí)現(xiàn)的,最后,調(diào)用原先原型上的?$mount?方法掛載。
// public mount method
Vue.prototype.$mount = function (
? el?: string | Element,
? hydrating?: boolean
): Component {
? el = el && inBrowser ? query(el) : undefined
? return mountComponent(this, el, hydrating)
}
$mount?方法支持傳入 2 個(gè)參數(shù),第一個(gè)是?el,它表示掛載的元素,可以是字符串,也可以是 DOM 對(duì)象,如果是字符串在瀏覽器環(huán)境下會(huì)調(diào)用?query?方法轉(zhuǎn)換成 DOM 對(duì)象的。第二個(gè)參數(shù)是和服務(wù)端渲染相關(guān),在瀏覽器環(huán)境下不需要傳第二個(gè)參數(shù)。
$mount?方法實(shí)際上會(huì)去調(diào)用?mountComponent?方法,這個(gè)方法定義在?src/core/instance/lifecycle.js?文件中:
export function mountComponent (
? vm: Component,
? el: ?Element,
? hydrating?: boolean
): Component {
? vm.$el = el
? if (!vm.$options.render) {
??? vm.$options.render = createEmptyVNode
??? if (process.env.NODE_ENV !== 'production') {
????? /* istanbul ignore if */
????? if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
??????? vm.$options.el || el) {
??????? warn(
????????? 'You are using the runtime-only build of Vue where the template ' +
????????? 'compiler is not available. Either pre-compile the templates into ' +
????????? 'render functions, or use the compiler-included build.',
????????? vm
??????? )
????? } else {
??????? warn(
????????? 'Failed to mount component: template or render function not defined.',
????????? vm
??????? )
????? }
??? }
? }
? callHook(vm, 'beforeMount')
? let updateComponent
? /* istanbul ignore if */
? if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
??? updateComponent = () => {
????? const name = vm._name
????? const id = vm._uid
????? const startTag = `vue-perf-start:${id}`
????? const endTag = `vue-perf-end:${id}`
????? mark(startTag)
????? const vnode = vm._render()
????? mark(endTag)
????? measure(`vue ${name} render`, startTag, endTag)
????? mark(startTag)
????? vm._update(vnode, hydrating)
????? mark(endTag)
????? measure(`vue ${name} patch`, startTag, endTag)
??? }
? } else {
??? updateComponent = () => {
????? vm._update(vm._render(), hydrating)
??? }
? }
? // we set this to vm._watcher inside the watcher's constructor
? // since the watcher's initial patch may call $forceUpdate (e.g. inside child
? // component's mounted hook), which relies on vm._watcher being already defined
? new Watcher(vm, updateComponent, noop, {
??? before () {
????? if (vm._isMounted) {
??????? callHook(vm, 'beforeUpdate')
????? }
??? }
? }, true /* isRenderWatcher */)
? hydrating = false
? // manually mounted instance, call mounted on self
? // mounted is called for render-created child components in its inserted hook
? if (vm.$vnode == null) {
??? vm._isMounted = true
??? callHook(vm, 'mounted')
? }
? return vm
}
從上面的代碼可以看到,mountComponent?核心就是先調(diào)用?vm._render?方法先生成虛擬 Node,再實(shí)例化一個(gè)渲染W(wǎng)atcher,在它的回調(diào)函數(shù)中會(huì)調(diào)用?updateComponent?方法,最終調(diào)用?vm._update?更新 DOM。
Watcher?在這里起到兩個(gè)作用,一個(gè)是初始化的時(shí)候會(huì)執(zhí)行回調(diào)函數(shù),另一個(gè)是當(dāng) vm 實(shí)例中的監(jiān)測(cè)的數(shù)據(jù)發(fā)生變化的時(shí)候執(zhí)行回調(diào)函數(shù)
函數(shù)最后判斷為根節(jié)點(diǎn)的時(shí)候設(shè)置?vm._isMounted?為?true, 表示這個(gè)實(shí)例已經(jīng)掛載了,同時(shí)執(zhí)行?mounted?鉤子函數(shù)。 這里注意?vm.$vnode?表示 Vue 實(shí)例的父虛擬 Node,所以它為?Null?則表示當(dāng)前是根 Vue 的實(shí)例。
總結(jié):
? ? 在執(zhí)行$mount的時(shí)候,vue會(huì)先判斷render函數(shù)是否存在,若存在,則執(zhí)行render編譯模板,若不存在,則判斷template,若template存在,則將template通過(guò)render函數(shù)編譯成Vnode,最后更新DOM,在這過(guò)程中,初始化時(shí)調(diào)用了Watcher類(lèi)來(lái)充當(dāng)觀(guān)察者模式,一旦vm實(shí)例中的數(shù)據(jù)發(fā)生變化,Watcher就執(zhí)行回調(diào)函數(shù)