挂载
mount
在上一篇Vue初始化结束后,调用了vm.$mount()挂载dom,渲染页面。但是现在为止,只分析了Vue的初始化过程,还未分析初始化后是如何挂载dom的。下面是初始化的最后检测到如果有 el 属性, 则调用 vm.$mount 方法挂载vm,那么vm.$mount又是在哪里定义的呢?
...
// 调用$mount()挂载,渲染页面
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}Runtime + Compiler 构建出来的 Vue.js,它的入口是 src/platforms/web/entry-runtime-with-compiler.js,在入口文件中定义了Vue.prototype.$mount
// runtime/index中的$mount
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
...
const options = this.$options
// resolve template/el and convert to render function
// 如果不存在render函数,将模版转换成 render 函数
if (!options.render) {
let template = options.template
// 如果存在模版
if (template) {
if (typeof template === 'string') {
...
} else if (template.nodeType) {
template = template.innerHTML
} else {
...
return this
}
} else if (el) {
template = getOuterHTML(el)
}
if (template) {
// 将模板编译成render函数
const { render, staticRenderFns } = compileToFunctions(template, ...)
options.render = render
options.staticRenderFns = staticRenderFns
...
}
}
// 调用runtime中的mount方法
return mount.call(this, el, hydrating)
}主要是关注if-else中的逻辑,如果options中不存在render函数时,将模版template转化成render函数(这里的编译比较复杂,之后也会进行单独的详细分析),最后调用runtime/index文件中定义的$mount。
Quiz Time👇
如果同时传入了 template 和 render,则渲染哪一个?
✅ 如果没有 render 函数,将 template 转换成 render;如果有 render,不管有没有 template,直接调用 mount 挂载 dom。需要通过调试来加深印象 mount的挂载过程。
mountComponent
上面提到了挂载最后调用了runtime/index文件中定义的$mount。在$mount中又调用了mountComponent方法:
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
// 获取el,因为运行时版本没有编译的过程
el = el && inBrowser ? query(el) : undefined
// 与浏览器无关的一个核心方法
return mountComponent(this, el, hydrating)
}mountComponent()主要完成的是整个渲染工作。
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 */
// 如果没有render方法,但传入了template,并且当前是开发环境时发送警告
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.render()生成的虚拟dom转换成真实dom
// _update会对比两个虚拟dom的差异,将虚拟dom转化为真实dom
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 && !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
}从源码中可以看出,主要定义了updateComponent方法,当创建watcher实例的时候传入它,在Watcher的构造函数中,最后会调用get()
get() {
pushTarget(this)
let value
const vm = this.vm
try {
// 当前是 renderWatcher,调用 updateComponent
value = this.getter.call(vm, vm)
} catch (e) {
...
} finally {
...
}
return value
}Quiz Time👇
这里提到的 watcher 是什么类型的 watcher?
✅ watcher的类型有三种:1. 计算属性 computed;2. 侦听器 用户watcher;3. 渲染 watcher。 ✅ 这里是渲染 watcher,作用有两个,一个是初始化的时候会执行回调函数(updateComponent),另一个是当 vm 实例中的监测的数据发生变化的时候执行回调函数(updateComponent)。
Watcher 在这里有两个作用,一个是初始化的时候执行回调,另一个是当 vm 实例中的监听数据发生变化的时候执行回调。
总结挂载过程
在Vue初始化的最后,检测到如果有 el 属性,则调用 vm.$mount 方法挂载vm,vm不能挂载在body或者html上,不能覆盖它们,挂载的目标就是把模板渲染成最终的 DOM,核心就是先实例化一个渲染Watcher(观察者模式),在它的回调函数中会调用 updateComponent 方法,在此方法中调用 vm.render 方法先生成虚拟 Node,最终调用 vm.update 更新DOM,构建dom tree。这部分需要通过调试加深印象,而且这其中包含patch的过程。下一篇将详细介绍updateComponent中的的两个核心方法,一个是vm._render方法和vm._update方法。