作者:王聪
本篇目的是介绍vue实例化到挂载到dom的整体路线,一些细节会被省略。
从new vue()开始
所有的一切都是从 new vue()开始的,所以从这个点开始探寻这个过程发生了什么。从中找到vue构造函数的声明,src/core/instance/index.js
import { initmixin } from './init'
import { statemixin } from './state'
import { rendermixin } from './render'
import { eventsmixin } from './events'
import { lifecyclemixin } from './lifecycle'
import { warn } from '../util/index'
function vue (options) {
if (process.env.node_env !== 'production' &&
!(this instanceof vue)
) {
warn('vue is a constructor and should be called with the `new` keyword')
}
this._init(options)
}
initmixin(vue)
statemixin(vue)
eventsmixin(vue)
lifecyclemixin(vue)
rendermixin(vue)
export default vue
是一个很简洁的function工厂模式声明的一个构造函数。
内部做了逻辑判断:构造函数调用必须有 new 关键字。
然后执行了this._init(options),该初始化函数就是vue 初始化的开始。
vue.prototype._init()
this._init()是在何时声明的呢?通过下边5个初始化函数的执行,在vue原型链中添加了大量的的属性与函数。this._init()实际就是调用了原型链上的vue.prototype._init()函数。
initmixin(vue) statemixin(vue) eventsmixin(vue) lifecyclemixin(vue) rendermixin(vue)
vue.prototype._init函数是在initmixin(vue)中去添加到原型链上的。在src/core/instance/init.js中定义
vue.prototype._init = function (options?: object) {
const vm: component = this
// a uid
vm._uid = uid++
let starttag, endtag
/* istanbul ignore if */
if (process.env.node_env !== 'production' && config.performance && mark) {
starttag = `vue-perf-start:${vm._uid}`
endtag = `vue-perf-end:${vm._uid}`
mark(starttag)
}
// a flag to avoid this being observed
vm._isvue = true
// merge options
if (options && options._iscomponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initinternalcomponent(vm, options)
} else {
vm.$options = mergeoptions(
resolveconstructoroptions(vm.constructor),
options || {},
vm
)
}
/* istanbul ignore else */
if (process.env.node_env !== 'production') {
initproxy(vm)
} else {
vm._renderproxy = vm
}
// expose real self
vm._self = vm
initlifecycle(vm)
initevents(vm)
initrender(vm)
callhook(vm, 'beforecreate')
initinjections(vm) // resolve injections before data/props
initstate(vm)
initprovide(vm) // resolve provide after data/props
callhook(vm, 'created')
/* istanbul ignore if */
if (process.env.node_env !== 'production' && config.performance && mark) {
vm._name = formatcomponentname(vm, false)
mark(endtag)
measure(`vue ${vm._name} init`, starttag, endtag)
}
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
}
}
_init函数内部又通过上边的这种调用初始化函数的模式完成了具体模块的初始化。声明钩子的调用也首次在这里出现,通过分析这些函数调用顺序,能更好的理解官方文档中提及的各个生命周期钩子函数的触发时机。
initlifecycle(vm) initevents(vm) initrender(vm) callhook(vm, 'beforecreate') initinjections(vm) // resolve injections before data/props initstate(vm) initprovide(vm) // resolve provide after data/props callhook(vm, 'created')
在_init()函数的最后,执行了vm.$mount()。vm代表的是当前vue实例也就是构造函数被调用后的this指向。
**$mount**是何时在vue上声明的呢?这次并不是在上边的初始化函数中完成声明的。因为 $mount 这个方法的实现是和平台、构建方式都相关,所以在不同构建入口文件中有不同的定义。
vue.prototype.$mount
原型上声明的 $mount方法在 src/platform/web/runtime/index.js 中定义,这个方法会被runtime only版本和含编译器完整版中复用,vue版本说明。
// public mount method
vue.prototype.$mount = function (
el?: string | element,
hydrating?: boolean
): component {
el = el && inbrowser ? query(el) : undefined
return mountcomponent(this, el, hydrating)
}
现在接着上边vue.prototype._init函数中调用了vm.$mount函数,实际上是执行了mountcomponent(this, el, hydrating)函数。
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)
}
}
// 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
}
抛开源码中对性能测试和异常警告部分的代码,这个函数内部做了以下事情:
callhook(vm, 'beforemount'),调用生命周期钩子beforemount 声明了updatecomponent函数 new watcher (vm, updatecomponent, noop, {... callhook(vm, 'beforeupdate')}}) callhook(vm, 'mounted'),调用生命周期钩子mounted这里的new watcher()实例化了watcher类,内部逻辑先不去深入,这里仅仅需要知道的是在这个实例化的过程中调用了作为参数传入的updatecomponent函数,而从这个函数的声明来看,它实际上执行的是vm._update(vm._render(), hydrating)这个函数。
首先vm._update和vm._render这两个方法是定义在vue原型上的。
vue.prototype._render
vue 的 _render 方法是用来把实例渲染成一个虚拟 node。是在rendermixin(vue)执行时声明的。它的定义在 src/core/instance/render.js 文件中
vue.prototype._render = function (): vnode {
const vm: component = this
const { render, _parentvnode } = vm.$options
// reset _rendered flag on slots for duplicate slot check
if (process.env.node_env !== 'production') {
for (const key in vm.$slots) {
// $flow-disable-line
vm.$slots[key]._rendered = false
}
}
if (_parentvnode) {
vm.$scopedslots = _parentvnode.data.scopedslots || emptyobject
}
// set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
vm.$vnode = _parentvnode
// render self
let vnode
try {
vnode = render.call(vm._renderproxy, vm.$createelement)
} catch (e) {
handleerror(e, vm, `render`)
// return error render result,
// or previous vnode to prevent render error causing blank component
/* istanbul ignore else */
if (process.env.node_env !== 'production') {
if (vm.$options.rendererror) {
try {
vnode = vm.$options.rendererror.call(vm._renderproxy, vm.$createelement, e)
} catch (e) {
handleerror(e, vm, `rendererror`)
vnode = vm._vnode
}
} else {
vnode = vm._vnode
}
} else {
vnode = vm._vnode
}
}
// return empty vnode in case the render function errored out
if (!(vnode instanceof vnode)) {
if (process.env.node_env !== 'production' && array.isarray(vnode)) {
warn(
'multiple root nodes returned from render function. render function ' +
'should return a single root node.',
vm
)
}
vnode = createemptyvnode()
}
// set parent
vnode.parent = _parentvnode
return vnode
}
函数内部对不同逻辑有不同的处理,但最终返回的都是vnode。
virtual dom 就是用一个原生的 js 对象去描述一个 dom 节点。
vue.prototype._update函数
_update是在lifecyclemixin(vue)函数执行时添加的。在目录src/core/instance/lifecycle.js
vue.prototype._update = function (vnode: vnode, hydrating?: boolean) {
const vm: component = this
const prevel = vm.$el
const prevvnode = vm._vnode
const restoreactiveinstance = setactiveinstance(vm)
vm._vnode = vnode
// vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
if (!prevvnode) {
// initial render
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeonly */)
} else {
// updates
vm.$el = vm.__patch__(prevvnode, vnode)
}
restoreactiveinstance()
// update __vue__ reference
if (prevel) {
prevel.__vue__ = null
}
if (vm.$el) {
vm.$el.__vue__ = vm
}
// if parent is an hoc, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el
}
// updated hook is called by the scheduler to ensure that children are
// updated in a parent's updated hook.
}
通过源码看接受的参数:
vnode: vnode hydrating?: boolean接受的第一个参数类型是vnode(用来描述dom节点的虚拟节点),第二个布尔类型的参数是跟ssr相关。
函数内部最关键的执行了vm.$el = vm.__patch__(...)
调用 vm.__patch__ 去把 vnode 转换成真正的 dom 节点
现在回顾总结一下目前的流程:
new vue()操作后,会调用vue.prototype._init()方法。完成一系列初始化(原型上添加方法和属性)执行vue.prototype.$mount
vm._render()获取描述当前实例的vnode vm._update(vnode),调用 vm.__patch__转换成真正的 dom 节点流程图:
NN-wow