vue2源码解析(三)
Vue实例挂载的实现
Vue中我们通过$mount实例方法去挂载vm的,$mount方法在多个文件中都有定义,如src/platform/web/entry-runtime-with-compiler.js,src/platform/web/runtime/index.js,src/platform/weex/runtime/index.js。因为这个方法跟平台,构建方式都相关的。下面我们重点看下entry-runtime-with-compiler.js中的实现:
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && query(el)
/* 对el 做出限制,Vue不能挂载到body,html这样的根节点上 */
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
}
const options = this.$options
// 如果没有 render 方法 就将 el 或者 template 转换为 render 方法
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, {
outputSourceRange: process.env.NODE_ENV !== 'production',
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方法,在重新定义该方法,我们先看重新定义的方法。首先它对el做了限制,Vue不能挂载到body,html这样的根节点上。接下来是很关键的逻辑————如果没有定义render方法,则会将el或者template字符串转换为render方法。
这点很重要在Vue2版本中,所有Vue组件的渲染最终都要通过render方法,无论我们用的是.vue单文件方式开发组件,还是写el和template属性,最终都会被转换为render方法,这个过程是Vue的一个"在线编译”的过程,它是调用comileFunctions方法实现的,最后调用之前缓存的$mount方法挂载。
之前缓存的$mount方法在src/platform/web/runtime/index.js中定义的,之所以这样设计是为了复用,因为它可以被runtime only版本的Vue直接使用。
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && inBrowser ? query(el) : undefined
return mountComponent(this, el, hydrating)
}
$mount方法支持传入2个参数,第一个是el,它表示挂载的元素,可以是字符串,也可以是DOM对象,如果是字符串在浏览器环境下会调用 query 方法转换成 DOM 对象的。第二个参数是和服务端渲染相关,在浏览器环境下我们不需要传第二个参数。
$mount实际上会去调用mountComponent方法,这个方法定义在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)
}
}
// 初始化的时候触发 updateComponent 函数 监听vm 数据变化的时候执行回调函数
// 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 && !vm._isDestroyed) {
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核心就是先实例化一个渲染Watcher,在它的回调函数中会调用updateComponent方法,在这个方法中调用vm._render方法生成虚拟Node,最终调用vm.update更新DOM。
Watcher在这里有两个作用,初始化时执行回调函数,vm实例中检测的数据发生变化时执行回调函数。
最后的判断如果是根节点的时候设置vm._isMounted为true,表示这个实例已经挂载了,同时执行mounted钩子函数。这里的vm.$vnode表示Vue实例的父虚拟Node,所有它为null时表示当前为根Vue的实例。