# 深入响应式原理
Vue的数据驱动,有一个很重要的体现就是数据的变更会触发DOM的变化。
<div id="app" @click="changeMsg">
{{ message }}
</div>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
},
methods: {
changeMsg() {
this.message = 'Hello World!'
}
}
})
这里假设我们不使用Vue的情况下,如何实现这个需求:监听点击事件,修改数据,手动操作DOM重新渲染。 这个过程最大的区别就是多了一步“手动操作DOM重新渲染”,这一步看上去并不多,但是背后有几个潜在的问题需要处理:
- 我们需要修改哪块DOM》
- 修改效率和性能是不是最优的?
- 我需要对数据每一次的修改都去操作DOM吗?
接下来了解Vue响应式系统的底层细节。
# 响应式对象
大多数人都知道Vue实现响应式的核心是利用ES5的Object.defineProperty
,这也是Vue.js不能兼容IE8及以下浏览器的原因。
- Object.defineProperty Object.defineProperty方式会直接在对象上定义一个新的属性,或者修改一个对象的现有属性,并返回这个对象
Object.defineProperty(obj, prop, descriptor)
obj是要在其上定义属性的对象;prop是要定义或者修改的属性名称;descriptor是将被定义或修改的属性描述符。 descriptor里面有两个方法set和get,get是一个给属性提供的getter方法,当我们访问属性的时候会触发getter方法;set是一个给属性提供setter方法,当我们对该属性进行修改时,会触发setter方法。 Vue中就是通过改写这两个方法,将对象编程响应式对象。
- initState
在Vue的初始化阶段,_init方法执行的时候,会执行
initState(vm)
,它定义在src/core/instance/state/js
export function initState (vm: Component) {
vm._watchers = []
const opts = vm.$options
if (opts.props) initProps(vm, opts.props)
if (opts.methods) initMethods(vm, opts.methods)
if (opts.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)
}
}
initState方法主要对props、methods、data、computed和watcher等属性进行初始化操作。
- initProps
function initProps (vm: Component, propsOptions: Object) {
const propsData = vm.$options.propsData || {}
const props = vm._props = {}
// cache prop keys so that future props updates can iterate using Array
// instead of dynamic object key enumeration.
const keys = vm.$options._propKeys = []
const isRoot = !vm.$parent
// root instance props should be converted
if (!isRoot) {
toggleObserving(false)
}
for (const key in propsOptions) {
keys.push(key)
const value = validateProp(key, propsOptions, propsData, vm)
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
const hyphenatedKey = hyphenate(key)
if (isReservedAttribute(hyphenatedKey) ||
config.isReservedAttr(hyphenatedKey)) {
warn(
`"${hyphenatedKey}" is a reserved attribute and cannot be used as component prop.`,
vm
)
}
defineReactive(props, key, value, () => {
if (vm.$parent && !isUpdatingChildComponent) {
warn(
`Avoid mutating a prop directly since the value will be ` +
`overwritten whenever the parent component re-renders. ` +
`Instead, use a data or computed property based on the prop's ` +
`value. Prop being mutated: "${key}"`,
vm
)
}
})
} else {
defineReactive(props, key, value)
}
// static props are already proxied on the component's prototype
// during Vue.extend(). We only need to proxy props defined at
// instantiation here.
if (!(key in vm)) {
proxy(vm, `_props`, key)
}
}
toggleObserving(true)
}
props的初始化过程,主要做了两件事,一个是调用defineReactive方法将每一个prop对应的值变成响应式的,另一个是通过proxy(vm, _props
, key)将props挂在到vm上
- initData
function initData (vm: Component) {
let data = vm.$options.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
)
}
}
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)) {
proxy(vm, `_data`, key)
}
}
// observe data
observe(data, true /* asRootData */)
}
data的初始化主要过程也是做两件事,一个是定义data函数返回对象的遍历,通过proxy把每一个值vm._data.xxx都代理到vm.xxx;另一个是调用observe方法,观测data的变化,把data也变成响应式
- proxy 代理的作用就是把props和data上的属性代理到vm实例上
let comP = {
props: {
msg: 'hello'
},
methods: {
say() {
console.log(this.msg)
}
}
}
我们可以在say函数中通过this.msg访问到我们定义在props中的msg,这个过程发生在proxy阶段
const sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
}
export function proxy (target: Object, sourceKey: string, key: string) {
sharedPropertyDefinition.get = function proxyGetter () {
return this[sourceKey][key]
}
sharedPropertyDefinition.set = function proxySetter (val) {
this[sourceKey][key] = val
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}
proxy的实现方式是通过Object.defineProperty把target[source][key]的读写变成了对target[key]的读写。 对props而言,对vm._props.xxx的读写就变成了vm.xxx的读写 对data而言,对vm._data.xxx的读写就变成了对vm.xxx的读写
- observe
observe的功能就是用来检测数据的变化,它定义在src/core/observer/index.js
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*/
export function observe (value: any, asRootData: ?boolean): Observer | void {
if (!isObject(value) || value instanceof VNode) {
return
}
let ob: Observer | void
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__
} else if (
shouldObserve &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value)
}
if (asRootData && ob) {
ob.vmCount++
}
return ob
}
observe方法的作用就是给非VNode的对象类型数据添加一个Observer,如果已经添加过则直接返回,否则在满足一定条件下去实例化一个Observer对象实例
- Observer Observer是一个类,作用是给对象的属性添加getter和setter,用于依赖收集和派发更新:
/**
* Observer class that is attached to each observed
* object. Once attached, the observer converts the target
* object's property keys into getter/setters that
* collect dependencies and dispatch updates.
*/
export class Observer {
value: any;
dep: Dep;
vmCount: number; // number of vms that has this object as root $data
constructor (value: any) {
this.value = value
this.dep = new Dep()
this.vmCount = 0
def(value, '__ob__', this)
if (Array.isArray(value)) {
const augment = hasProto
? protoAugment
: copyAugment
augment(value, arrayMethods, arrayKeys)
this.observeArray(value)
} else {
this.walk(value)
}
}
/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
walk (obj: Object) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i])
}
}
/**
* Observe a list of Array items.
*/
observeArray (items: Array<any>) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
}
Observer的构造函数逻辑很简单,首先实例化Dep对象,然后通过def函数把自身的实例添加到数据对象value的__ob__属性上,def的定义在src/core/util/lang.js
中
/**
* Define a property.
*/
export function def (obj: Object, key: string, val: any, enumerable?: boolean) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: true,
configurable: true
})
}
def函数就是堆Object.defineProperty的封装,这又是为什么在开发中输出data上对象类型的数据,会发现多了一个__ob__的属性 在Observer的构造函数中,会对value作判断,如果是数组的话,会调用observeArray方法,否则调用walk方法 而walk方法是遍历对象,然后执行defineReactive方法
- defineReactive
defineReactive的功能就是定义一个响应式对象,给对象动态添加getter和setter,它定义在src/core/observer/index.js
中:
/**
* Define a reactive property on an Object.
*/
export function defineReactive (
obj: Object,
key: string,
val: any,
customSetter?: ?Function,
shallow?: boolean
) {
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
if ((!getter || setter) && arguments.length === 2) {
val = obj[key]
}
let childOb = !shallow && observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
dep.depend()
if (childOb) {
childOb.dep.depend()
if (Array.isArray(value)) {
dependArray(value)
}
}
}
return value
},
set: function reactiveSetter (newVal) {
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()
}
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
dep.notify()
}
})
}
defineReactive函数最开始初始化Dep对象的实例,接着拿到obj的属性描述符,然后对子对象递归调用observe方法,这样就能保证无论obj的结果多复杂,它的所有子属性也能变成响应式的对象。 最后利用Object.defineProperty去给obj的属性key添加getter和setter。
# 依赖收集
Vue会把普通对象变成响应式对象,响应式对象getter相关的逻辑爱就是做依赖收集
export function defineReactive (
obj: Object,
key: string,
val: any,
customSetter?: ?Function,
shallow?: boolean
) {
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
if ((!getter || setter) && arguments.length === 2) {
val = obj[key]
}
let childOb = !shallow && observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
dep.depend()
if (childOb) {
childOb.dep.depend()
if (Array.isArray(value)) {
dependArray(value)
}
}
}
return value
},
// ...
})
}
这里需要注意两个地方,一个是const dep = new Dep() 实例化一个Dep的实例,另一个是在get函数中通过dep.depend做依赖收集
- Dep
Dep是整个getter依赖收集的核心,定义在
src/core/observer/dep.js
中
import type Watcher from './watcher'
import { remove } from '../util/index'
let uid = 0
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
export default class Dep {
static target: ?Watcher;
id: number;
subs: Array<Watcher>;
constructor () {
this.id = uid++
this.subs = []
}
addSub (sub: Watcher) {
this.subs.push(sub)
}
removeSub (sub: Watcher) {
remove(this.subs, sub)
}
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
notify () {
// stabilize the subscriber list first
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
// the current target watcher being evaluated.
// this is globally unique because there could be only one
// watcher being evaluated at any time.
Dep.target = null
const targetStack = []
export function pushTarget (_target: ?Watcher) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = _target
}
export function popTarget () {
Dep.target = targetStack.pop()
}
Dep是一个Class,它定义了一些属性和方法,这里需要特别注意的是它有一个静态属性target,这是一个全局唯一Watcher,在同一时间只能有一个全局的Watcher被计算,它自身的属性subs也是Watcher的数组
Dep实际上就是对Watcher的一种管理,Dep脱离Watcher单独存在是没有意义的
- Watcher
let uid = 0
/**
* A watcher parses an expression, collects dependencies,
* and fires callback when the expression value changes.
* This is used for both the $watch() api and directives.
*/
export default class Watcher {
vm: Component;
expression: string;
cb: Function;
id: number;
deep: boolean;
user: boolean;
computed: boolean;
sync: boolean;
dirty: boolean;
active: boolean;
dep: Dep;
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
if (isRenderWatcher) {
vm._watcher = this
}
vm._watchers.push(this)
// options
if (options) {
this.deep = !!options.deep
this.user = !!options.user
this.computed = !!options.computed
this.sync = !!options.sync
this.before = options.before
} else {
this.deep = this.user = this.computed = this.sync = false
}
this.cb = cb
this.id = ++uid // uid for batching
this.active = true
this.dirty = this.computed // for computed watchers
this.deps = []
this.newDeps = []
this.depIds = new Set()
this.newDepIds = new Set()
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 = function () {}
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
)
}
}
if (this.computed) {
this.value = undefined
this.dep = new Dep()
} else {
this.value = this.get()
}
}
/**
* Evaluate the getter, and re-collect dependencies.
*/
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
}
/**
* Add a dependency to this directive.
*/
addDep (dep: Dep) {
const id = dep.id
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id)
this.newDeps.push(dep)
if (!this.depIds.has(id)) {
dep.addSub(this)
}
}
}
/**
* Clean up for dependency collection.
*/
cleanupDeps () {
let i = this.deps.length
while (i--) {
const dep = this.deps[i]
if (!this.newDepIds.has(dep.id)) {
dep.removeSub(this)
}
}
let tmp = this.depIds
this.depIds = this.newDepIds
this.newDepIds = tmp
this.newDepIds.clear()
tmp = this.deps
this.deps = this.newDeps
this.newDeps = tmp
this.newDeps.length = 0
}
// ...
}
Watcher是一个Class,在它的构造函数中,定义了一些和Dep相关的属性:
this.deps = []
this.newDeps = []
this.depIds = new Set()
this.newDepIds = new Set()
其中。this.deps和this.newDeps表示Watcher实例持有的Dep实例的数组;而this.depIds和this.newDepIds分别代表this.deps和this.newDeps的id Set。
Watcher还定义了一些原型的方法,和依赖收集相关的有get、addDep和cleanDeps方法。
- 过程分析 对数据对象访问会触发他们的getter,那么这些对象什么时候被访问呢,在Vue的mount过程是通过mountComponent函数,其中有一段
updateComponent = () => {
vm._update(vm._render(), hydrating)
}
new Watcher(vm, updateComponent, noop, {
before () {
if (vm._isMounted) {
callHook(vm, 'beforeUpdate')
}
}
}, true /* isRenderWatcher */)
当我们去实例化一个Watcher的时候,首先会进入watcher的构造函数,最后会执行它的this.get()方法,进入get函数,首先会执行:
pushTarget(this)
pushTarget的定义在src/core/observer/dep.js
中
export function pushTarget (_target: ?Watcher) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = _target
}
实际上就是把Dep.target赋值为当前的渲染watcher并压栈(为了恢复用)。接着又执行了:
value = this.getter.call(vm, vm)
this.getter对应就是updateComponent函数,实际上执行的就行
vm._update(vm._render(), hydrating)
它会先执行vm._render()方法,因为之前分析过这个方法会生成VNode,并且在这个过程中,会对vm上的数据访问,这个时候就触发了数据对象的getter
那么每个对象值的getter都持有一个dep,在触发getter的时候会调用dep.depend()方法,也就是会执行Dep.target.addDep(this)
刚才我们提到这个时候Dep.target已经被赋值为渲染watcher,那么就执行到addDep方法:
addDep (dep: Dep) {
const id = dep.id
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id)
this.newDeps.push(dep)
if (!this.depIds.has(id)) {
dep.addSub(this)
}
}
}
这时候会做一些逻辑判断(保证同一数据不会被添加多次)后执行dep.addSub(this),也就是this.sub.push(sub),就是把当前的watcher订阅到这个数据持有的dep的subs中,这个目的是为了后续数据变化的时候能通知到哪些subs做准备。
所以在vm._render()过程中,会触发所有的getter,这样实际上已经完成了一个依赖收集的过程。依赖收集后,还有几个逻辑要执行:
if (this.deep) {
traverse(value)
}
这个是要递归去访问value,触发所有子项的getter
popTarget()
popTarget定义在src/core/observer/dep.js
Dep.target = targetStack.pop()
实际上就是把Dep.target恢复成上一个状态,因为当前vm的数据依赖收集已经完成,那么对应渲染的Dep.target也需要改变,最后执行
this.cleanupDeps()
进行依赖清空
cleanupDeps () {
let i = this.deps.length
while (i--) {
const dep = this.deps[i]
if (!this.newDepIds.has(dep.id)) {
dep.removeSub(this)
}
}
let tmp = this.depIds
this.depIds = this.newDepIds
this.newDepIds = tmp
this.newDepIds.clear()
tmp = this.deps
this.deps = this.newDeps
this.newDeps = tmp
this.newDeps.length = 0
}
考虑到Vue是数据驱动的,所以每次数据变化都会重新render,那么vm._render()方法又会再次执行,并再次触发数据的getters,所以Watcher在构造函数中会初始化两个Dep实例数组,newDeps表示新的,deps表示上一次的
在执行cleanupDeps函数式,会先遍历deps,移除对dep的订阅,然后把newDepIds和depIds交互,newDeps和deps交换,并把newDepIds和newDeps清空。
为什么要做deps订阅的移除呢,在添加deps的订阅过程,已经能通过id去重避免重复定位了。
考虑到一种场景,我们的模板会根据v-if去渲染不同的子模板a和b,当我们满足某种条件的时候渲染a时,会访问a中的数据,这时候我们对a使用的数据添加了getter,做了依赖收集,那么我们修改a的数据时,就会通知这些订阅者。 如果我们修改了条件转而渲染b模板,又会对b使用的数据添加getter,如果我们没有依赖移除的过程,那么我们去修改a的时候,还会通知a数据的订阅的回调,显然是浪费的。
因此Vue设计了再每次添加完新的订阅,会移除掉旧的订阅,这样就能刚才所说的场景下,如果渲染 b 模板的时候去修改 a 模板的数据,a 数据订阅回调已经被移除了,不造成性能的浪费。
brief:收集依赖的目的就是为了这些响应式数据发送变化时,会触发它们的setter从而通知订阅者去做相应的逻辑处理,这个过程我们叫作派发更新。
# 派发更新
响应式数据的依赖收集,目的就是为了我们修改数据的时候,可以对相关的依赖派发更新 这里回顾一下setter的部分逻辑
/**
* Define a reactive property on an Object.
*/
export function defineReactive (
obj: Object,
key: string,
val: any,
customSetter?: ?Function,
shallow?: boolean
) {
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
if ((!getter || setter) && arguments.length === 2) {
val = obj[key]
}
let childOb = !shallow && observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
// ...
set: function reactiveSetter (newVal) {
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()
}
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
dep.notify()
}
})
}
这里有两个关键点,一个是 childOb = !shallow && observe(newVal),如果shallow为false的情况,会将新设置的值变成一个响应式对象; 另一个是dep.notify(),通知所有的订阅者。
# 检测变化的注意事项
有几种特殊情况下,Vue是无法检测到响应式对象的改变
- 对象添加属性 对于使用Object.defineProperty实现响应式对象,但我们去给这个对象添加一个新的属性的时候,是无法出发它的setter的
var vm = new Vue({
data:{
a:1
}
})
// vm.b 是非响应的
vm.b = 2
这里我们可以使用Vue.set方法解决这个问题,它定义在src/core/observer/index.js
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
export function set (target: Array<any> | Object, key: any, val: any): any {
if (process.env.NODE_ENV !== 'production' &&
(isUndef(target) || isPrimitive(target))
) {
warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: any)}`)
}
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.length = Math.max(target.length, key)
target.splice(key, 1, val)
return val
}
if (key in target && !(key in Object.prototype)) {
target[key] = val
return val
}
const ob = (target: any).__ob__
if (target._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
)
return val
}
if (!ob) {
target[key] = val
return val
}
defineReactive(ob.value, key, val)
ob.dep.notify()
return val
}
set接受三个参数,target是数组或对象,key代表数组的下标或者对象的键值,val代表添加的值。首先判断如果target是数组且key是一个合法的下标,则之前通过splice去添加数组然后返回(这里的splice是vue改写后的splice)。 接在再获取到target.ob,如果它不存在则说明target不是一个响应式对象,最后通过defineReactive(ob.value, key, val)把新添加的属性变成响应式对象,然后通过ob.dep.notify()手动的触发依赖。
# 计算属性和侦听属性
- computed
计算属性的初始化发生在Vue实例初始化阶段initState函数中,initComputed定义在
src/core/instance/state.js
中
const computedWatcherOptions = { computed: true }
function initComputed (vm: Component, computed: Object) {
// $flow-disable-line
const watchers = vm._computedWatchers = Object.create(null)
// computed properties are just getters during SSR
const isSSR = isServerRendering()
for (const key in computed) {
const userDef = computed[key]
const getter = typeof userDef === 'function' ? userDef : userDef.get
if (process.env.NODE_ENV !== 'production' && getter == null) {
warn(
`Getter is missing for computed property "${key}".`,
vm
)
}
if (!isSSR) {
// create internal watcher for the computed property.
watchers[key] = new Watcher(
vm,
getter || noop,
noop,
computedWatcherOptions
)
}
// component-defined computed properties are already defined on the
// component prototype. We only need to define computed properties defined
// at instantiation here.
if (!(key in vm)) {
defineComputed(vm, key, userDef)
} else if (process.env.NODE_ENV !== 'production') {
if (key in vm.$data) {
warn(`The computed property "${key}" is already defined in data.`, vm)
} else if (vm.$options.props && key in vm.$options.props) {
warn(`The computed property "${key}" is already defined as a prop.`, vm)
}
}
}
}
函数首先会创造一个vm._computedWatchers为一个空对象。接着对computed属性进行遍历,拿到每一个属性的userDef,然后尝试获取对应的userDef或者getter(拿不到则报错),这个渲染watcher和render watcher有一个不同,是options里面的computed属性为true,即表明其为computed watcher,最后会判断key是不是vm的属性,如果不是则调用defineComputed,否则报错。
defineComputed
export function defineComputed (
target: any,
key: string,
userDef: Object | Function
) {
const shouldCache = !isServerRendering()
if (typeof userDef === 'function') {
sharedPropertyDefinition.get = shouldCache
? createComputedGetter(key)
: userDef
sharedPropertyDefinition.set = noop
} else {
sharedPropertyDefinition.get = userDef.get
? shouldCache && userDef.cache !== false
? createComputedGetter(key)
: userDef.get
: noop
sharedPropertyDefinition.set = userDef.set
? userDef.set
: noop
}
if (process.env.NODE_ENV !== 'production' &&
sharedPropertyDefinition.set === noop) {
sharedPropertyDefinition.set = function () {
warn(
`Computed property "${key}" was assigned to but it has no setter.`,
this
)
}
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}
defineComputed就是调用Object.defineProperty给计算属性对应的key值添加getter和setter。 计算属性的getter对应的为createComputedGetter的返回值
function createComputedGetter (key) {
return function computedGetter () {
const watcher = this._computedWatchers && this._computedWatchers[key]
if (watcher) {
watcher.depend()
return watcher.evaluate()
}
}
}
createComputedGetter返回一个函数computedGetter,即该计算属性对应的getter。
简单分析一个computed watcher的实现。
var vm = new Vue({
data: {
firstName: 'Foo',
lastName: 'Bar'
},
computed: {
fullName: function () {
return this.firstName + ' ' + this.lastName
}
}
})
初始化时
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
// ...
if (this.computed) {
this.value = undefined
this.dep = new Dep()
} else {
this.value = this.get()
}
}
可以发现computed不会立刻求职,并且会持有一个dep实例
然后render函数访问到this.fullName的时候,就会触发计算属性的getter,它会拿到计算属性对应的watcher,然后执行计算属性的watcher,并执行watcher.depend()
/**
* Depend on this watcher. Only for computed property watchers.
*/
depend () {
if (this.dep && Dep.target) {
this.dep.depend()
}
}
这时候的Dep.target是render watcher,所以ths.dep.depend()相当于渲染watcher订阅了这个computed watcher的变化
然后执行watcher.evaluate()去求值。
/**
* Evaluate and return the value of the watcher.
* This only gets called for computed property watchers.
*/
evaluate () {
if (this.dirty) {
this.value = this.get()
this.dirty = false
}
return this.value
}
evaluate的逻辑非常简单,判断this.dirty,如果为true则执行this.get()求值,然后把this.dirty设置为false。 在求值过程中会执行value=this.getter.call(vm,vm),实际上就是执行了计算属性定义的getter函数(在这个例子中就是return this.firstName + '' + this.lastName) 这里会触发this.firstName和this.lastName的getter,也就会把自身持有的dep添加到当前正在计算的watcher中,这个时候Dep.target就是这个computed watcher 最后通过return this.value拿到计算属性对应的值。 一旦我们对计算属性依赖的数据做修改,则会触发setter过程,通知所有订阅它变化的watcher更新,执行watcher.update()方法。
/* istanbul ignore else */
if (this.computed) {
// A computed property watcher has two modes: lazy and activated.
// It initializes as lazy by default, and only becomes activated when
// it is depended on by at least one subscriber, which is typically
// another computed property or a component's render function.
if (this.dep.subs.length === 0) {
// In lazy mode, we don't want to perform computations until necessary,
// so we simply mark the watcher as dirty. The actual computation is
// performed just-in-time in this.evaluate() when the computed property
// is accessed.
this.dirty = true
} else {
// In activated mode, we want to proactively perform the computation
// but only notify our subscribers when the value has indeed changed.
this.getAndInvoke(() => {
this.dep.notify()
})
}
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
那么对于计算属性这样的computed watcher,它实际上有2种模式,lazy和active。如果this.dep.subs.length === 0 ,则说明没人去订阅这个computed watcher的变化,仅仅把this.dirty = true,只有当下次再访问这个计算属性的时候才会重新求值。
这里讨论如果渲染watcher订阅了这个computed watcher的变化,它会执行
this.getAndInvoke(() => {
this.dep.notify()
})
getAndInvoke (cb: Function) {
const value = this.get()
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) ||
this.deep
) {
// set new value
const oldValue = this.value
this.value = value
this.dirty = false
if (this.user) {
try {
cb.call(this.vm, value, oldValue)
} catch (e) {
handleError(e, this.vm, `callback for watcher "${this.expression}"`)
}
} else {
cb.call(this.vm, value, oldValue)
}
}
}
getAndInvoke函数会重新甲酸,然后比对新旧值,如果变化了则执行回调函数(即this.dep.notify()),在这个场景下就是触发了渲染watcher重新渲染。
通过分析,我们知道计算属性的本质就是computed watcher,之所以这么设计是因为Vue想确保不仅仅是计算属性依赖的值发生变化,而是当计算属性最终计算的值变化才触发watcher重新渲染。
- watch
侦听属性的初始化也是发生在Vue的实例初始化阶段的initState函数中,在computed初始化之后,执行了
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
来看一下initWatch的实现,它的定义在src/core/instance/state.js
中
function initWatch (vm: Component, watch: Object) {
for (const key in watch) {
const handler = watch[key]
if (Array.isArray(handler)) {
for (let i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i])
}
} else {
createWatcher(vm, key, handler)
}
}
}
这里就是对watch对象做遍历,拿到每一个handler,因为Vue是支持watch的同一个key对应多个handler,所以如果handler是一个数组,则遍历这个数组,调用createWatcher方法,否则直接调用createWatcher
function createWatcher (
vm: Component,
expOrFn: string | Function,
handler: any,
options?: Object
) {
if (isPlainObject(handler)) {
options = handler
handler = handler.handler
}
if (typeof handler === 'string') {
handler = vm[handler]
}
return vm.$watch(expOrFn, handler, options)
}
这里的逻辑,首先对handler的类型做判断,拿到它最终的回调函数,最后执行vm.$watch(keyOrFn, handler, options)函数,$watch是Vue原型上的方法,在stateMixin的时候定义:
Vue.prototype.$watch = function (
expOrFn: string | Function,
cb: any,
options?: Object
): Function {
const vm: Component = this
if (isPlainObject(cb)) {
return createWatcher(vm, expOrFn, cb, options)
}
options = options || {}
options.user = true
const watcher = new Watcher(vm, expOrFn, cb, options)
if (options.immediate) {
cb.call(vm, watcher.value)
}
return function unwatchFn () {
watcher.teardown()
}
}
侦听属性watch最终会调用$watch方法,这个方法首先判断cb如果是一个对象,则调用createWatcher方法,这是因为$watch方法是用户可以直接调用的,它可以传递一个对象,也可以传递函数。
接着执行const watcher = new Watcher(vm, expOrFn, cb, options)
实例化一个watche,因为options.user = true,所以这里为初始化一个user watcher
。
如果watch的数据发生变化,最终会执行watcher的run方法,执行回调函数cb,如果设置了immediate为true,则会立即执行函数。
最后返回了一个unwatchFn方法,它会调用teardown方法去移除这个watcher。
所以本质上侦听属性也是基于Watcher实现的,它是一个user watcher,其实watcher也支持不同的类型。
- Watcher options
Watch的构造函数对options做的了处理,代码如下:
if (options) {
this.deep = !!options.deep
this.user = !!options.user
this.computed = !!options.computed
this.sync = !!options.sync
// ...
} else {
this.deep = this.user = this.computed = this.sync = false
}
所以watcher总共有4种类型
- deep watcher
通常我们想对一个对象做深度观测的时候,需要设置这个属性
var vm = new Vue({
data() {
a: {
b: 1
}
},
watch: {
a: {
handler(newVal) {
console.log(newVal)
}
}
}
})
vm.a.b = 2
这里不会触发a的watch,因为只会订阅到a的getter,不会订阅到a.b的getter。 需要将其修改成
watch: {
a: {
deep: true,
handler(newVal) {
console.log(newVal)
}
}
}
这样就创建了一个deep watcher,在watcher执行get求值的过程中有一段逻辑
get() {
let value = this.getter.call(vm, vm)
// ...
if (this.deep) {
traverse(value)
}
}
traverse函数定义在src/core/observer/traverse.js
中
import { _Set as Set, isObject } from '../util/index'
import type { SimpleSet } from '../util/index'
import VNode from '../vdom/vnode'
const seenObjects = new Set()
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*/
export function traverse (val: any) {
_traverse(val, seenObjects)
seenObjects.clear()
}
function _traverse (val: any, seen: SimpleSet) {
let i, keys
const isA = Array.isArray(val)
if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) {
return
}
if (val.__ob__) {
const depId = val.__ob__.dep.id
if (seen.has(depId)) {
return
}
seen.add(depId)
}
if (isA) {
i = val.length
while (i--) _traverse(val[i], seen)
} else {
keys = Object.keys(val)
i = keys.length
while (i--) _traverse(val[keys[i]], seen)
}
}
traverse实际上就是对一个对象进行深层递归遍历,遍历过程中会对触发子对象的getter,这样就能收集到依赖,也就是订阅它们变化的watcher。 那么在执行了traverse后,我们再对watch的对象内部任何一个值做修改,也会调用watcher的回调函数。
- user watcher
没有任何options时,通过vm.$watch创建的一个最基本的watcher
- computed watcher
计算属性
- sync watcher
当响应式数据发生变化后,触发了watcher.update(),只是把watcher推送到一个队列中,然后在nextTick后才会真正的执行watcher的回调函数。 如果设置了sync为true,就会在当前Tick中同步执行watcher的回调函数。
update () {
if (this.computed) {
// ...
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
}
当需要watch的值变化时,回调为一个同步函数,才需要去设置sync值。
brief:通过对watcher的了解,计算属性本质上是computed watcher,而侦听属性实际上是user watcher。 计算属性适合用于模板渲染中,某个值是依赖其他响应式对象甚至是计算属性而来,不宜做大量和复杂的处理。 侦听属性适用于观测某个值去完成一段复杂的业务逻辑。
# 组件更新
当数据发生变化的时候,会触发watcher的回调函数,进而执行组件的更新过程。接下来分析这个过程。
updateComponent = () => {
vm._update(vm._render(), hydrating)
}
new Watcher(vm, updateComponent, noop, {
before () {
if (vm._isMounted) {
callHook(vm, 'beforeUpdate')
}
}
}, true /* isRenderWatcher */)
组件的更新调用了vm._update方法,定义在src/core/instance/lifeCycle.js
中
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
const vm: Component = this
// ...
const prevVnode = vm._vnode
if (!prevVnode) {
// initial render
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
} else {
// updates
vm.$el = vm.__patch__(prevVnode, vnode)
}
// ...
}
组件更新的过程,会执行vm.$el = vm.patch(prevVnode, vnode),它仍然会调用patch函数,在src/core/vdom/patch.js
中
return function patch (oldVnode, vnode, hydrating, removeOnly) {
if (isUndef(vnode)) {
if (isDef(oldVnode)) invokeDestroyHook(oldVnode)
return
}
let isInitialPatch = false
const insertedVnodeQueue = []
if (isUndef(oldVnode)) {
// empty mount (likely as component), create new root element
isInitialPatch = true
createElm(vnode, insertedVnodeQueue)
} else {
const isRealElement = isDef(oldVnode.nodeType)
if (!isRealElement && sameVnode(oldVnode, vnode)) {
// patch existing root node
patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly)
} else {
if (isRealElement) {
// ...
}
// replacing existing element
const oldElm = oldVnode.elm
const parentElm = nodeOps.parentNode(oldElm)
// create new node
createElm(
vnode,
insertedVnodeQueue,
// extremely rare edge case: do not insert if old element is in a
// leaving transition. Only happens when combining transition +
// keep-alive + HOCs. (#4590)
oldElm._leaveCb ? null : parentElm,
nodeOps.nextSibling(oldElm)
)
// update parent placeholder node element, recursively
if (isDef(vnode.parent)) {
let ancestor = vnode.parent
const patchable = isPatchable(vnode)
while (ancestor) {
for (let i = 0; i < cbs.destroy.length; ++i) {
cbs.destroy[i](ancestor)
}
ancestor.elm = vnode.elm
if (patchable) {
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, ancestor)
}
// #6513
// invoke insert hooks that may have been merged by create hooks.
// e.g. for directives that uses the "inserted" hook.
const insert = ancestor.data.hook.insert
if (insert.merged) {
// start at index 1 to avoid re-invoking component mounted hook
for (let i = 1; i < insert.fns.length; i++) {
insert.fns[i]()
}
}
} else {
registerRef(ancestor)
}
ancestor = ancestor.parent
}
}
// destroy old node
if (isDef(parentElm)) {
removeVnodes(parentElm, [oldVnode], 0, 0)
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode)
}
}
}
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch)
return vnode.elm
}
这里执行patch的逻辑和首次渲染不一样,因为oldVnode不为空,并且它和vnode都是VNode类型,接下来会通过sameVNode(oldVnode, vnode)判断他们是否是相同的vnode来觉得走不同的更新逻辑
function sameVnode (a, b) {
return (
a.key === b.key && (
(
a.tag === b.tag &&
a.isComment === b.isComment &&
isDef(a.data) === isDef(b.data) &&
sameInputType(a, b)
) || (
isTrue(a.isAsyncPlaceholder) &&
a.asyncFactory === b.asyncFactory &&
isUndef(b.asyncFactory.error)
)
)
)
}
sameVnode,首先判断两个vnode的key是否相等,否则继续判断对于同步组件,则判断isComment、data、input类似是否相等,对于异步组件则判断asyncFactory是否相等。 所有根据新旧vnode是否为sameVnode,会走到不同的更新逻辑。
- 新旧节点不同
如果新旧vnode不同,那么逻辑本质就是要替换已存在的节点,这其中分为三步
- 创建新节点
const oldElm = oldVnode.elm
const parentElm = nodeOps.parentNode(oldElm)
// create new node
createElm(
vnode,
insertedVnodeQueue,
// extremely rare edge case: do not insert if old element is in a
// leaving transition. Only happens when combining transition +
// keep-alive + HOCs. (#4590)
oldElm._leaveCb ? null : parentElm,
nodeOps.nextSibling(oldElm)
)
以当前旧节点为参考节点,创建新的节点,并插入DOM中
- 更新父节点的占位符
// update parent placeholder node element, recursively
if (isDef(vnode.parent)) {
let ancestor = vnode.parent
const patchable = isPatchable(vnode)
while (ancestor) {
for (let i = 0; i < cbs.destroy.length; ++i) {
cbs.destroy[i](ancestor)
}
ancestor.elm = vnode.elm
if (patchable) {
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, ancestor)
}
// #6513
// invoke insert hooks that may have been merged by create hooks.
// e.g. for directives that uses the "inserted" hook.
const insert = ancestor.data.hook.insert
if (insert.merged) {
// start at index 1 to avoid re-invoking component mounted hook
for (let i = 1; i < insert.fns.length; i++) {
insert.fns[i]()
}
}
} else {
registerRef(ancestor)
}
ancestor = ancestor.parent
}
}
这里的主要逻辑是找到当前vnode的父的占位节点,先执行各个module的destory的钩子函数,如果当前占位符是一个可挂载的节点,则执行module的create函数。
- 删除旧节点
// destroy old node
if (isDef(parentElm)) {
removeVnodes(parentElm, [oldVnode], 0, 0)
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode)
}
把oldVnode从当前DOM树中删除,如果父节点存在,则执行removeVnodes方法:
function removeVnodes (parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
const ch = vnodes[startIdx]
if (isDef(ch)) {
if (isDef(ch.tag)) {
removeAndInvokeRemoveHook(ch)
invokeDestroyHook(ch)
} else { // Text node
removeNode(ch.elm)
}
}
}
}
function removeAndInvokeRemoveHook (vnode, rm) {
if (isDef(rm) || isDef(vnode.data)) {
let i
const listeners = cbs.remove.length + 1
if (isDef(rm)) {
// we have a recursively passed down rm callback
// increase the listeners count
rm.listeners += listeners
} else {
// directly removing
rm = createRmCb(vnode.elm, listeners)
}
// recursively invoke hooks on child component root node
if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) {
removeAndInvokeRemoveHook(i, rm)
}
for (i = 0; i < cbs.remove.length; ++i) {
cbs.remove[i](vnode, rm)
}
if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {
i(vnode, rm)
} else {
rm()
}
} else {
removeNode(vnode.elm)
}
}
function invokeDestroyHook (vnode) {
let i, j
const data = vnode.data
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.destroy)) i(vnode)
for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode)
}
if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j])
}
}
}
删除的逻辑就是遍历待删除的vnodes做删除。 其中removeAndInvokeRemoveHook的作用是从DOM中移除节点并执行module的remove钩子函数,并对它的子节点递归调用removeAndInvokeRemoveHook函数。 invokeDestoryHook是执行module的destory钩子函数,以及vnode的destpry钩子函数,并对它的子vnode递归调用invokeDestoryHook函数,removeNode就是调用平台的DOM API去把真正的DOM节点移除。
- 新旧节点相同
对于新旧节点相同的情况,对调用patchVnode方法,定义在src/core/vdom/patch.js
中
function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) {
if (oldVnode === vnode) {
return
}
const elm = vnode.elm = oldVnode.elm
if (isTrue(oldVnode.isAsyncPlaceholder)) {
if (isDef(vnode.asyncFactory.resolved)) {
hydrate(oldVnode.elm, vnode, insertedVnodeQueue)
} else {
vnode.isAsyncPlaceholder = true
}
return
}
// reuse element for static trees.
// note we only do this if the vnode is cloned -
// if the new node is not cloned it means the render functions have been
// reset by the hot-reload-api and we need to do a proper re-render.
if (isTrue(vnode.isStatic) &&
isTrue(oldVnode.isStatic) &&
vnode.key === oldVnode.key &&
(isTrue(vnode.isCloned) || isTrue(vnode.isOnce))
) {
vnode.componentInstance = oldVnode.componentInstance
return
}
let i
const data = vnode.data
if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) {
i(oldVnode, vnode)
}
const oldCh = oldVnode.children
const ch = vnode.children
if (isDef(data) && isPatchable(vnode)) {
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode)
if (isDef(i = data.hook) && isDef(i = i.update)) i(oldVnode, vnode)
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly)
} else if (isDef(ch)) {
if (isDef(oldVnode.text)) nodeOps.setTextContent(elm, '')
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue)
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1)
} else if (isDef(oldVnode.text)) {
nodeOps.setTextContent(elm, '')
}
} else if (oldVnode.text !== vnode.text) {
nodeOps.setTextContent(elm, vnode.text)
}
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.postpatch)) i(oldVnode, vnode)
}
}
这里关键步骤有四步:
- 执行prepatch钩子函数
let i
const data = vnode.data
if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) {
i(oldVnode, vnode)
}
当更新的vnode是一个组件vnode的时候会执行prepatch的方法,定义在src/core/vdom/create-component.js
const componentVNodeHooks = {
prepatch (oldVnode: MountedComponentVNode, vnode: MountedComponentVNode) {
const options = vnode.componentOptions
const child = vnode.componentInstance = oldVnode.componentInstance
updateChildComponent(
child,
options.propsData, // updated props
options.listeners, // updated listeners
vnode, // new parent vnode
options.children // new children
)
}
}
prepatch方法就是拿到新的vnode的组件配置以及组件实例,去执行updateChildComponent方法,它定义在src/core/instance/lifecycle.js
中
export function updateChildComponent (
vm: Component,
propsData: ?Object,
listeners: ?Object,
parentVnode: MountedComponentVNode,
renderChildren: ?Array<VNode>
) {
if (process.env.NODE_ENV !== 'production') {
isUpdatingChildComponent = true
}
// determine whether component has slot children
// we need to do this before overwriting $options._renderChildren
const hasChildren = !!(
renderChildren || // has new static slots
vm.$options._renderChildren || // has old static slots
parentVnode.data.scopedSlots || // has new scoped slots
vm.$scopedSlots !== emptyObject // has old scoped slots
)
vm.$options._parentVnode = parentVnode
vm.$vnode = parentVnode // update vm's placeholder node without re-render
if (vm._vnode) { // update child tree's parent
vm._vnode.parent = parentVnode
}
vm.$options._renderChildren = renderChildren
// update $attrs and $listeners hash
// these are also reactive so they may trigger child update if the child
// used them during render
vm.$attrs = parentVnode.data.attrs || emptyObject
vm.$listeners = listeners || emptyObject
// update props
if (propsData && vm.$options.props) {
toggleObserving(false)
const props = vm._props
const propKeys = vm.$options._propKeys || []
for (let i = 0; i < propKeys.length; i++) {
const key = propKeys[i]
const propOptions: any = vm.$options.props // wtf flow?
props[key] = validateProp(key, propOptions, propsData, vm)
}
toggleObserving(true)
// keep a copy of raw propsData
vm.$options.propsData = propsData
}
// update listeners
listeners = listeners || emptyObject
const oldListeners = vm.$options._parentListeners
vm.$options._parentListeners = listeners
updateComponentListeners(vm, listeners, oldListeners)
// resolve slots + force update if has children
if (hasChildren) {
vm.$slots = resolveSlots(renderChildren, parentVnode.context)
vm.$forceUpdate()
}
if (process.env.NODE_ENV !== 'production') {
isUpdatingChildComponent = false
}
}
- 执行update钩子函数
if (isDef(data) && isPatchable(vnode)) {
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode)
if (isDef(i = data.hook) && isDef(i = i.update)) i(oldVnode, vnode)
}
回到patchVNode函数,在执行完新的vnode的prepatch钩子函数,会执行所有module的update钩子函数以及用户自定义update钩子函数,对于module的钩子函数。
- 完成patch过程
const oldCh = oldVnode.children
const ch = vnode.children
if (isDef(data) && isPatchable(vnode)) {
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode)
if (isDef(i = data.hook) && isDef(i = i.update)) i(oldVnode, vnode)
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly)
} else if (isDef(ch)) {
if (isDef(oldVnode.text)) nodeOps.setTextContent(elm, '')
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue)
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1)
} else if (isDef(oldVnode.text)) {
nodeOps.setTextContent(elm, '')
}
} else if (oldVnode.text !== vnode.text) {
nodeOps.setTextContent(elm, vnode.text)
}
如果vnode是个文本节点且新旧文本不同,则直接替换,如果不是文本节点,则判断它们的子节点:
- oldch与ch都存在切不相等,调用updateChildren
- 如果只有ch存在,表示旧节点已不需要了。如果旧的节点是文本节点则先将节点的文本清楚,然后通过addVnodes将ch插入新节点elm下
- 如果只有oldCh存在,则表明更新的是空节点,将旧节点通过removeVnode清楚
- 只有旧节点是文本节点时候,则清楚节点文本内容
- 执行postpatch钩子函数
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.postpatch)) i(oldVnode, vnode)
}
再执行完patch过程后,会执行postpatch钩子函数,它是组件定义的钩子函数,有则执行。
brief: 组件更新的过程核心就是新旧vnode diff,对新旧节点相同以及不同的情况分别做不同的处理。新旧节点不同的更新流程是1、创建新节点 2、更新父占位符节点 3、删除旧节点;而新节点相同的更新流程是去获取它们的children,根据不同情况做不同的更新逻辑。最复杂的情况是新旧节点相同且它们都存在子节点,那么会执行updateChildren逻辑。
原理图