Vue源码探秘(四)(实例挂载$mount)

引言

在上一篇文章的结尾,咱们提到数据渲染到DOM的关键就是调用vm.$mount方法来挂载vm。这一步是在_init函数的结尾被调用的:html

// src/core/instance/init.js
Vue.prototype._init = function (options?: Object) {
// ...
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
}
复制代码

本篇文章,咱们来分析一下vm.$mount内部具体发生了什么。vue

实例挂载($mount)

回顾以前的文章,咱们知道$mount被定义在src/platforms/web/runtime/index.js中:node

// 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方法,在src/platform/web/entry-runtime-with-compiler.jssrc/platform/weex/runtime/index.js都有定义。由于$mount方法的实现是和平台、构建方式都相关的。web

在运行时(Runtime Only)版本的Vue中,调用的就是上面的这个$mount函数。而在完整版(Runtime + Compiler)的Vue中,$mount函数在src/platform/web/entry-runtime-with-compiler.js中被重写,这部分代码是咱们这里要着重分析的。先看一下总体结构:缓存

// src/platforms/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)

// ...

return mount.call(this, el, hydrating);
}
复制代码

这里先拿到了Runtime Only版本的$mount方法,而后进行重写,最后又调用了Runtime Only版本的$mount方法。参数的类型检查代表el能够是字符串或DOM节点。接下来又调用了query方法:weex

// src/platforms/web/util/index.js
/**
* Query an element selector if it's not an element already.
*/

export function query (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
)
return document.createElement('div')
}
return selected
} else {
return el
}
}
复制代码

query函数的逻辑比较简单: 若是el是一个字符串,就调用querySelector获取节点并返回;若是节点不存在就抛出警告并建立一个div节点。若是el是一个节点就直接返回。app

咱们接着往下分析,先来看第一小段:编辑器

/* 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
}
复制代码

这里去检查el是否是根节点(html)、(body),若是是就抛出警告并中止挂载。ide

Vue是不能挂载在bodyhtml这样的根节点上的,由于挂载实际上就是把el节点替换为组件的模版。函数

继续往下看:

const options = this.$options
// resolve template/el and convert to render function
if (!options.render) {
let template = options.template
if (template) {
// [1] ...
} else if (el) {
template = getOuterHTML(el)
}
// [2] ...
}
复制代码

首先判断render函数是否存在,若是未定义则需作进一步处理。

Vue2.0 开始,全部组件的渲染都须要用到render函数,不管是咱们上一节的例子仍是使用.vue文件编写。

进入if判断后先拿到options.template,若是template存在就执行[1]处的代码:

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
}
复制代码

先判断template是不是字符串,若是是字符串并且是id选择器,经过idToTemplate方法拿到相应节点,若是拿不到会抛出警告。若是是字符串但不是选择器,不做处理。

若是template是一个节点,那么获取它的innerHTML

若是template既不是字符串也不是一个节点,那么抛出警告并结束挂载。

若是template不存在,接着判断el是否存在,存在则执行template = getOuterHTML(el)。来看下getOuterHTML函数:

// src/platforms/web/entry-runtime-with-compiler.js
/**
* Get outerHTML of elements, taking care
* of SVG elements in IE as well.
*/

function getOuterHTML (el: Element): string {
if (el.outerHTML) {
return el.outerHTML
} else {
const container = document.createElement('div')
container.appendChild(el.cloneNode(true))
return container.innerHTML
}
}
复制代码

这里判断el.outerHTML是否存在,有就返回outerHTML

IE9-11SVG 标签元素是没有 innerHTMLouterHTML 这两个属性的。

else中就是对以上状况的兼容处理: 在el的外面包装了一层div,而后获取该divinnerHTML

这样不管是 template 仍是 el ,都被转为了字符串模板,而后执行[2]处的代码:

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')
}
}
复制代码

这里先判断template是否存在(template可能为空字符串)。能够清楚的看到进入if语句内,里面有两个相同的if语句,这与咱们以前介绍_init函数时遇到的同样,都是用于性能追踪。

中间这段代码调用了compileToFunctions函数,返回的render函数将其挂载到options.render上。关于compileToFunctions的具体实现,我会在后面的章节中详细介绍。

最后执行了:

return mount.call(this, el, hydrating)
复制代码

这里是调用以前缓存的在src/platforms/web/runtime/index.js中定义的$mount函数:

// src/platforms/web/runtime/index.js

// 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 又把 el 从字符串转换成了节点而后传给了 mountComponent 函数。和上面同样,这里把 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')

// ...
}
复制代码

先将el保存到vm.$el上,而后判断前面的template是否被正确的转换成了render函数。若是转换失败,将createEmptyVNode做为render函数。createEmptyVNode函数会建立一个空的VNode对象。这部分会放在后面章节介绍。

在非生产环境下(通常是开发版本下),若是编写了template或者el的同时又使用了Runtime Only版本的Vue,致使在$mount中不能编译成render函数,则会抛出警告;另外若是既没有template也没有render函数也会抛出警告。

接下来调用的callHook函数是生命周期相关,会在后面的生命周期章节详细介绍。继续往下看:

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)
}
}
复制代码

if语句里面是再熟悉不过的性能追踪,咱们直接跳过,看else部分。

这里面定义了一个updateComponent函数,涉及到两个函数:

  • _render: 调用 vm.$options.render 函数并返回生成的虚拟节点( VNode
  • _update: 将 VNode 渲染成真实 DOM

这里我只是大概说明一下它的做用,具体会在后面章节中展开。

接着往下看:

// 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
复制代码

这里建立了一个 Watcher 实例,显然是与响应式数据相关的。这里的 Watcher 也仅作了解,在后面的章节会具体分析。

Watcher 会解析表达式,收集依赖关系,而且在表达式的值发生改变时触发回调。Watcher 在这里主要有两个做用: 一个是初始化的时候会执行回调函数;另外一个是当 vm 实例中监测的数据发生变化的时候执行回调函数,而回调函数就是传入的 updateComponent 函数。

回到 mountComponent 函数,还剩最后一段代码:

// 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
复制代码

函数最后判断为根节点的时候设置 vm._isMountedtrue, 表示这个实例已经挂载了,同时执行 mounted 钩子函数。

这里注意 vm.$vnode 表示 Vue 实例的父虚拟 Node,因此它为 Null 则表示当前是根 Vue 的实例。

总结

这一节咱们分析了 $mount 函数的大致执行流程,下一篇文章我将介绍 $mount 函数中_render 函数的实现。

相关文章
相关标签/搜索