Vue源码探秘(四)(实例挂载$mount)
2020/3/21 11:01:32
本文主要是介绍Vue源码探秘(四)(实例挂载$mount),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
引言
在上一篇文章的结尾,我们提到数据渲染到DOM
的关键就是调用vm.$mount
方法来挂载vm
。这一步是在_init
函数的结尾被调用的:
// src/core/instance/init.js Vue.prototype._init = function (options?: Object) { // ... if (vm.$options.el) { vm.$mount(vm.$options.el) } } 复制代码
本篇文章,我们来分析一下vm.$mount
内部具体发生了什么。
实例挂载($mount)
回顾之前的文章,我们知道$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
方法,在src/platform/web/entry-runtime-with-compiler.js
、src/platform/weex/runtime/index.js
都有定义。因为$mount
方法的实现是和平台、构建方式都相关的。
在运行时(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
方法:
// 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
是一个节点就直接返回。
我们接着往下分析,先来看第一小段:
/* 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
),如果是就抛出警告并停止挂载。
Vue
是不能挂载在body
、html
这样的根节点上的,因为挂载实际上就是把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
函数是否存在,如果未定义则需做进一步处理。
从
Vue
2.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-11
中SVG
标签元素是没有innerHTML
和outerHTML
这两个属性的。
else
中就是对以上情况的兼容处理: 在el
的外面包装了一层div
,然后获取该div
的innerHTML
。
这样无论是 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._isMounted
为 true
, 表示这个实例已经挂载了,同时执行 mounted
钩子函数。
这里注意
vm.$vnode
表示Vue
实例的父虚拟 Node
,所以它为Null
则表示当前是根Vue
的实例。
总结
这一节我们分析了 $mount
函数的大体执行流程,下一篇文章我将介绍 $mount
函数中_render
函数的实现。
这篇关于Vue源码探秘(四)(实例挂载$mount)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04package.json 文件位置在哪?-icode9专业技术文章分享
- 2024-10-01Craco.js学习:从入门到实践指南
- 2024-10-01Create-React-App学习:入门与实践指南
- 2024-10-01CSS-in-JS学习:从入门到实践指南
- 2024-09-30JSX语法学习:从入门到初步掌握
- 2024-09-30Mock.js学习:入门教程与实战演练
- 2024-09-30React Hooks学习:从入门到实践
- 2024-09-30受控组件学习:React中的基础入门教程
- 2024-09-29JS定时器教程:初学者必看指南
- 2024-09-29JS对象教程:初学者的全面指南