请你说说Vue实例挂载过程中发生了什么?
1. 前言
相信大家在面试过程中都遇到过这个问题:new Vue()
这个过程中究竟做了些什么?这个问题的考点是看你对Vue
底层原理的了解,在回答过程中如果能够从JS
对象的初始化开始,说清楚Vue
实例化的过程,最好再把生命周期的执行结合进来,那么这个问题可以回答的很优秀。
本文将尝试带大家从源码的层面去分析和理解,Vue实例挂载过程中发生的事情。
下面是官网的生命周期运行图:
2. 源码分析
在 Vue 源码中,Vue 构造函数的定义是在/src/core/instance
下,入口文件index.js
中,具体代码如下所示:
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)
}
Vue 的构造函数接收一个参数 options
, 就是我们实例化 Vue 对象时配置的参数,这个参数是一个Json
对象,包含el
, data
, components
,method
等。
2.1. 对象初始化
实例化Vue对象的时候,实际只执行已经在 Vue 构造函数原型上定义的_init
方法,_init
实现源码如下所示:
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 { // 合并vue属性
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
)
}
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
// 初始化proxy拦截器
initProxy(vm)
} else {
vm._renderProxy = vm
}
// expose real self
vm._self = vm
// 初始化组件生命周期标志位
initLifecycle(vm)
// 初始化组件事件侦听
initEvents(vm)
// 初始化渲染方法
initRender(vm)
callHook(vm, 'beforeCreate')
// 初始化依赖注入内容,在初始化data、props之前
initInjections(vm) // resolve injections before data/props
// 初始化props/data/method/watch/methods
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)
}
}
从上面的源码中,我们可以清晰的看到在 Vue 的生命周期每个阶段具体做了什么事,比如:
- 在
beforeCreate
中,访问不到data
数据,mergeOptions
是合并实例和mixins/extend
上的数据,返回值vm.$options
是合并后实例上的属性,data
数据返回是一个function
,因为属性data
的合并策略是返回一个function
。 - 在
created
时,不能访问到DOM
对象,因为此时模板文件还没有编译,还没有生成具体的DOM
元素。在created
之前,只是对组件中的数据进行了初始化,编译template
和生成vnode
,到生成真实DOM
挂载到页面上,是在vm.$mount
方法中一步步执行的。
2.2. 数据初始化
Vue 是一个支持双向数据绑定的一个框架,Vue2的双向数据绑定是基于Object.defineProperty
的get
和set
通过数据劫持模式实现的,在get
中进行依赖收集,set
中进行派发更新。但是数据是如何初始化的呢?以data
为例,我们来看下Vue
是如何进行数据初始化的。
在对象初始化的代码里,我们知道在beforeCreate
后,会走进initState
方法,initState
中,会分别对props
, methods
, data
和watch
进行初始化,如下所示:
export function initState (vm: Component) {
// 初始化组件的watcher列表
vm._watchers = []
const opts = vm.$options
if (opts.props) initProps(vm, opts.props)
if (opts.methods) initMethods(vm, opts.methods)
if (opts.data) {
// 初始化data
initData(vm)
} else {
observe(vm._data = {}, true /* asRootData */)
}
if (opts.computed) initComputed(vm, opts.computed)
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
在initData
函数里面,data
在 mergeOptions
时,返回的是一个 function
。
在获取data
数据时,需要执行这个方法。
initData
代码如下:
function initData (vm: Component) {
let data = vm.$options.data
// 获取到组件上的data
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
if (!isPlainObject(data)) {
data = {}
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
)
}
// proxy data on instance
const keys = Object.keys(data)
const props = vm.$options.props
const methods = vm.$options.methods
let i = keys.length
while (i--) {
const key = keys[i]
if (process.env.NODE_ENV !== 'production') {
// 属性名不能与方法名重复
if (methods && hasOwn(methods, key)) {
warn(
`Method "${key}" has already been defined as a data property.`,
vm
)
}
}
// 属性名不能与state名称重复
if (props && hasOwn(props, key)) {
process.env.NODE_ENV !== 'production' && warn(
`The data property "${key}" is already declared as a prop. ` +
`Use prop default value instead.`,
vm
)
} else if (!isReserved(key)) { // 验证key值的合法性
// 将_data中的数据挂载到组件vm上,这样就可以通过this.xxx访问到组件上的数据
proxy(vm, `_data`, key)
}
}
// observe data
// 响应式监听data是数据的变化
observe(data, true /* asRootData */)
}
getData
代码如下:
export function getData (data: Function, vm: Component): any {
// #7573 disable dep collection when invoking data getters
pushTarget()
try {
// 调用在属性合并时,返回的data
return data.call(vm, vm)
} catch (e) {
handleError(e, vm, `data()`)
return {}
} finally {
popTarget()
}
}
这里面有pushTarget
和 popTarget
,这里主要是用于保证无论何时,执行的组件监听计算只有一个,这个具体后面再讨论。
getData
的返回值就是合并后的data
对象,赋值到当前的实例属性。接下来有个while
循环,里面主要做三件事:
- 判断我们声明的
data
变量的合法性,我们声明变量的名称一定不要与methods
或者props
中的属性名重复,这也是许多新手容易犯的错误 - 声明变量的时候,不要用以
_
或者$
开头的变量,这些可能会导致声明变量和Vue
私有变量冲突 - 将
data
中的变量代理到vm
(组件实例)上,按照this
的指向性原理,data
对象中的this
应该指向data
,而不应该指向vm
,这里做了一层封装代理,具体代码如下:
// 属性代理,从一个原对象中拿数据
export function proxy (target: Object, sourceKey: string, key: string) {
// 设置对象属性的get/set,将data中的数据代理到组件对象vm上
sharedPropertyDefinition.get = function proxyGetter () {
return this[sourceKey][key]
}
sharedPropertyDefinition.set = function proxySetter (val) {
this[sourceKey][key] = val
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}
接下来下一步所需要执行的内容就比较重要了,需要对data
对象添加响应式侦听,调用observe
方法。
observe
方法代码如下:
export function observe (value: any, asRootData: ?boolean): Observer | void {
if (!isObject(value) || value instanceof VNode) {
return
}
let ob: Observer | void
// 存在__ob__属性的一般为观察者对象的实例
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__
} else if ( // Object.isExtensible 判断对象是否是可扩展的(可以添加新属性)
shouldObserve &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) { // 必须为数组 || 对象,才能实例化观察者对象
ob = new Observer(value)
}
if (asRootData && ob) {
ob.vmCount++
}
return ob
}
每一个响应式对象,都会有__ob__
属性,这个是Vue
中在声明响应式属性时定义的,如果没有该属性,数据的变化就不会被监测到,其他的可以暂时忽略,初始化响应对象是实例化了Observe
类。
Observer
类的具体实现如下:
export class Observer {
value: any;
dep: Dep;
vmCount: number; // number of vms that have this object as root $data
constructor (value: any) {
this.value = value
// 实例化一个发布-订阅模型
this.dep = new Dep()
this.vmCount = 0
// 给监听对象定义一个__ob__属性,属性值为this,指向当前实例
// 存在该属性的对象,就是响应式对象
def(value, '__ob__', this)
// 数组类型
if (Array.isArray(value)) {
// 存在原型 __proto__,重写数组原型上的方法
if (hasProto) {
protoAugment(value, arrayMethods)
} else {
// 不存在原型,则在数组中复制重写后的数组方法
copyAugment(value, arrayMethods, arrayKeys)
}
// 响应式监听数组的变化
this.observeArray(value)
} else {
// 如果值的类型为Object,则响应式的声明对象属性
this.walk(value)
}
}
在实例化时,有两个分支,一个是数组,一个是对象,在实例化时,都会数据的中定义__ob__
属性,值为当前观察者对象。
我们先看对象的响应式声明方式,调用this.walk
,具体代码如下:
walk (obj: Object) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
// 响应式定义对象属性的get set
defineReactive(obj, keys[i])
}
}
defineReactive
是重点,添加对象属性的get
、set
。
get
和set
中进行的数据劫持,实现代码如下:
export function defineReactive (
obj: Object,
key: string,
val: any,
customSetter?: ?Function,
shallow?: boolean
) {
// 初始化一个发布-订阅模型,每个对象都包含一个dep实例
const dep = new Dep()
// 获取属性描述符
const property = Object.getOwnPropertyDescriptor(obj, key)
// 对象的属性应该是可扩展、可配置的
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
const getter = property && property.get
const setter = property && property.set
// 处理obj的值
if ((!getter || setter) && arguments.length === 2) {
val = obj[key]
}
// 如果val值存在Object,则需要侦听val值的变化
let childOb = !shallow && observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
// 依赖收集 @todo
if (Dep.target) {
dep.depend()
if (childOb) {
childOb.dep.depend()
if (Array.isArray(value)) {
dependArray(value)
}
}
}
return value
},
set: function reactiveSetter (newVal) {
// 派发更新 @todo
// 获取到value数据
const value = getter ? getter.call(obj) : val
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter()
}
// #7981: for accessor properties without setter
if (getter && !setter) return
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
// 重新更新下数据依赖
childOb = !shallow && observe(newVal)
// 通知数据更新???@todo
dep.notify()
}
})
}
任何数据的读取,都会走到get
方法中,数据的更新,都会走get
、set
。其中在set
中,dep.notify
会派发更新页面数据。至此,data
初始化工作算是完成了。
2.3. 模板解析编译
数据初始化完成后,接下来需要做的就是解析template
和挂载dom
。
在src\platforms\web\entry-runtime-with-compiler.js
文件中,定义了$mount
方法,具体代码如下:
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
// 获取或查询元素
el = el && query(el)
/* istanbul ignore if */
// vue 不允许直接挂载到body或页面文档上
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
// resolve template/el and convert to render function
if (!options.render) {
let template = options.template
// 存在template模板,解析vue模板文件
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')
}
/**
* 1.将temmplate解析ast tree
* 2.将ast tree转换成render语法字符串
* 3.生成render方法
*/
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)
}
看完上面的代码,我们记一下发现:
- 不要将根元素放到
body
或者html
上 - 在
Vue
中,可以在对象中定义template
,render
或者直接使用template
、el
表示元素选择器,用法比较灵活 - 无论哪种写法,最终都会解析成
render
函数,调用compileToFunctions
,会将template
解析成render
函数
template
的解析步骤大致分为以下几步:
- 将
html
文档片段解析成ast
描述符 - 将
ast
描述符解析成字符串 - 生成
render
函数
如下图所示:template
生成render
函数,挂载到vm
上后,会再次调用mount
方法,这个mount
方法不是entry-runtime-with-compiler.js
复写的这个,是Vue
原型上的方法在src\platforms\web\runtime\index.js
中,里面会调用mountComponent
方法,具体如下:
// public mount method
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && inBrowser ? query(el) : undefined
// 渲染组件
return mountComponent(this, el, hydrating)
}
2.4. 页面挂载
src\core\instance\lifecycle.js
export function mountComponent (
vm: Component,
el: ?Element,
hydrating?: boolean
): Component {
vm.$el = el
// 如果没有获取解析的render函数,则会抛出警告
// render是解析模板文件生成的
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 {
// 没有获取到vue的模板文件
warn(
'Failed to mount component: template or render function not defined.',
vm
)
}
}
}
// 执行beforeMount钩子
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
}
这个方法中主要流程是:
- 调用了
beforeMount
钩子函数 - 定义
updateComponent
方法,是渲染DOM
的入口方法 - 对
vm
添加监听,实例化一个watcher
,然后调用updateComponent
方法 - 调用
mounted
声明周期钩子,至此组件实例化结束
Watcher类代码如下:
export default class Watcher {
vm: Component;
expression: string;
cb: Function;
id: number;
deep: boolean;
user: boolean;
lazy: boolean;
sync: boolean;
dirty: boolean;
active: boolean;
deps: Array<Dep>;
newDeps: Array<Dep>;
depIds: SimpleSet;
newDepIds: SimpleSet;
before: ?Function;
getter: Function;
value: any;
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
this.vm = vm
// 是渲染的watcher @todo
if (isRenderWatcher) {
vm._watcher = this
}
// 将vm添加到组件的_watchers队列中
vm._watchers.push(this)
// options
if (options) {
this.deep = !!options.deep
this.user = !!options.user
this.lazy = !!options.lazy
this.sync = !!options.sync
this.before = options.before
} else {
this.deep = this.user = this.lazy = this.sync = false
}
this.cb = cb
this.id = ++uid // uid for batching
this.active = true
this.dirty = this.lazy // for lazy watchers
this.deps = []
this.newDeps = []
this.depIds = new Set()
this.newDepIds = new Set()
// updateComponents
this.expression = process.env.NODE_ENV !== 'production'
? expOrFn.toString()
: ''
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn
} else {
this.getter = parsePath(expOrFn)
if (!this.getter) {
this.getter = noop
process.env.NODE_ENV !== 'production' && warn(
`Failed watching path: "${expOrFn}" ` +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
)
}
}
this.value = this.lazy
? undefined
: this.get()
}
/**
* Evaluate the getter, and re-collect dependencies.
* 执行更新组件的方法,先将当前要执行的watcher推入到执行队列中 @todo
*/
get () {
pushTarget(this)
let value
const vm = this.vm
try {
value = this.getter.call(vm, vm)
} catch (e) {
if (this.user) {
handleError(e, vm, `getter for watcher "${this.expression}"`)
} else {
throw e
}
} finally {
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value)
}
popTarget()
this.cleanupDeps()
}
return value
}
看起来很长,其实主要就是调用在上述第二步声明的updateComponent
方法,updateComponent
方法主要执行在Vue
初始化时声明的_render
、_update
方法。其中,_render
的作用主要是生成vnode
。_update
主要功能是调用__patch__
。将vnode
转换为真实DOM
,并且更新到页面中,具体如下:
// 定义vue 原型上的render方法
Vue.prototype._render = function (): VNode {
const vm: Component = this
// render函数来自于组件的option
const { render, _parentVnode } = vm.$options
if (_parentVnode) {
vm.$scopedSlots = normalizeScopedSlots(
_parentVnode.data.scopedSlots,
vm.$slots,
vm.$scopedSlots
)
}
// 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 {
// There's no need to maintain a stack because all render fns are called
// separately from one another. Nested component's render fns are called
// when parent component is patched.
currentRenderingInstance = vm
// 调用render方法,自己的独特的render方法, 传入createElement参数,生成vNode
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' && 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
}
} finally {
currentRenderingInstance = null
}
// if the returned array contains only a single node, allow it
if (Array.isArray(vnode) && vnode.length === 1) {
vnode = vnode[0]
}
// 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
}
_update
函数代码如下:
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.
}
从上面的源码中我们可以发现在挂载DOM
的过程中,是先添加新数据生成的节点,然后再移除老的节点。
3. 总结
简言之,Vue实例在挂载过程中大概做了这么几件事情:
new Vue
的时候调用会调用_init
方法
-
- 定义 set、set、set、get 、delete、delete、delete、watch 等方法
- 定义 on、on、on、off、emit、emit、emit、off等事件
- 定义 _update、forceUpdate、forceUpdate、forceUpdate、destroy生命周期
- 调用
$mount
进行页面的挂载 - 挂载的时候主要是通过
mountComponent
方法 - 定义
updateComponent
更新函数 - 执行
render
生成虚拟DOM
_update
将虚拟DOM
生成真实DOM
结构,并且渲染到页面中
转载自:https://juejin.cn/post/7255967761805574181