响应式
响应式原理是Vue的重中之重,也是MVVM的核心。一些基础的内容通过官方文档即可获知,这里将更注重对于源码的探索和一些场景的思考,例如数组的响应式处理。
Object.defineProperty
Vue2 将对象变成响应式对象依赖于 Object.defineProperty,该方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性,并返回此对象。它的语法是:
Object.defineProperty(obj, prop, descriptor)descriptor中我们关心的是get和set两个键,get是该属性的 getter 函数,如果没有 getter,则为 undefined。当访问该属性时,会调用此函数。同理,set 是一个给属性提供的 setter 方法,当我们对该属性做修改的时候会触发 setter 方法。一旦对象拥有了 getter 和 setter,我们可以简单地把这个对象称为响应式对象。
Proxy
ES2015 中定义了Proxy这个类,它用于创建一个对象的代理,从而实现基本操作的拦截和自定义(如属性查找、赋值、枚举、函数调用等)。在Vue源码响应式中主要是将props和data上的属性代理到vm实例上,所以平时使用时可以直接通过vm实例访问到它。
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)
}这里将对target[sourceKey][key]的读写变成了对target[key]的读写,对于props来说,对 vm._props.xxx 的读写变成了 vm.xxx 的读写,因此访问 vm._props.xxx 我们可以访问到定义在 props 中的属性。
不过Proxy在vue2中运用并不多,主要在vue3中实现响应式对象发挥着巨大的威力,同时也弥补了vue2响应式中的一些问题
响应式入口
在 Vue 的初始化阶段,_init 方法执行的时候,会执行 initState(vm) 方法,它的定义在 src/core/instance/state.js 中,它主要是用来初始化vm的_props/methods/_data/computed/watch。
export function initState(vm: Component) {
vm._watchers = []
const opts = vm.$options
// 将opts.props变成响应式注入到vue实例中
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)
}
}先只看data的响应式处理,如果options中不存在data,调用observe,且第一个参数赋值为{}。这就是响应式入口。当data有值时,进入initData。
function initData(vm: Component) {
let data = vm.$options.data
// 初始化_data,组件中data是函数,调用函数返回结果
// 如果是vue实例的话,直接返回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
// 判断data上的成员是否和props/methods重名
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代理,设置proxyGetter和proxySetter
proxy(vm, `_data`, key)
}
}
// observe data 响应式的起点
observe(data, true /* asRootData */)
}这里首先判断了data的类型,这是因为在单文件组件中,data必须是函数;其次判断data上的成员是否和props/methods重名,最后同样调用了observe() Q:为什么 data 必须是函数? A: 维护自身的一个实例
Observer
上面我们已经找到了响应式的起点,即触发observe(),observe中又去创建了一个observer对象。
export function observe(value: any, asRootData: ?boolean): Observer | void {
// 判断value是否是对象
if (!isObject(value) || value instanceof VNode) {
return
}
let ob: Observer | void
// 如果value有__ob__ 属性,相当于做过响应式处理
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
) {
// 创建一个observer对象
ob = new Observer(value)
}
if (asRootData && ob) {
ob.vmCount++
}
return ob
}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
// 将实例挂载到被 observe 对象的__ob__属性,不可枚举,只是用来记录observer对象
def(value, '__ob__', this)
// 数组的响应式处理
if (Array.isArray(value)) {
// 判断当前浏览器是否有对象原型
// 修补会改变原数组的方法,当这些方法调用时,调用dep.notify,通知更新视图
// 修补后的方法设置到数组对象的原型上
if (hasProto) {
protoAugment(value, arrayMethods)
} else {
// 若不支持__proto__
copyAugment(value, arrayMethods, arrayKeys)
}
// 为数组中的对象元素创建一个observer实例,
this.observeArray(value)
} else {
// 遍历对象中的每一个属性,转换何曾getter/setter
this.walk(value)
}
}
/**
* Walk through all properties 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实例,判断了即将处理的数据的类型,如果是数组的话,将做数组的响应式特殊处理(这个后面会说到);如果不是,则遍历该纯对象的每一个属性,通过调用defineReactive设置为响应式数据。
defineReactive
export function defineReactive(
obj: Object,
key: string,
val: any,
customSetter?: ?Function,
shallow?: boolean
) {
// 创建依赖对象实例,用来收集依赖于当前属性的订阅者 watcher
// 每个属性都有对应的dep
// 收集每个属性的依赖
const dep = new Dep()
// 获取 obj 的属性描述符对象
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]
}
// 判断是否深度监听,递归 observe 子对象,并将子对象属性都转换成getter/setter。返回child Observer
let childOb = !shallow && observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter() {
// 先调用用户传入的getter, 存在则value等于getter 调用的返回值
// 否则直接赋予属性值
const value = getter ? getter.call(obj) : val
// 如果存在当前依赖目标,即watcher对象存在,则收集依赖
if (Dep.target) {
dep.depend()
// 如果存在子 observer 存在,建立子对象的依赖关系
if (childOb) {
// 为子对象收集依赖,这个dep跟当前属性的dep是不同的,以数组为例,数组的dep对应的数组本身,为什么要给子对象加上dep呢?因为子对象添加删除等操作也需要是响应式,也就是数组的元素发生改变时也需要发送通知,$set $delete
childOb.dep.depend()
//属性是数组时,则特殊处理收集数组对象依赖
if (Array.isArray(value)) {
// 数组中的元素也是对象时,也要变成响应式,如果是数组,继续递归
dependArray(value)
}
}
}
return value
},
set: function reactiveSetter(newVal) {
// 使用预定义的getter获取旧值value
const value = getter ? getter.call(obj) : val
/* eslint-disable no-self-compare */
// 若新值等于旧值或者新值旧值为nan时不执行,因为nan不等于自身
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
}
// 若新值是对象,observe 子对象并返回child observer对象
childOb = !shallow && observe(newVal)
// 派发更新
dep.notify()
}
})
}defineReactive 的核心就在于将对象的key添加getter和setter,在getter中收集依赖,在setter中派发更新;同时会对子对象递归调用observe,保证对象的子属性都能变成响应式数据。接下来将着重分析一下收集依赖和派发更新两个过程。
收集依赖
收集依赖的关键代码就在于const dep = new Dep() 创建了一个Dep实例,然后在 dep.depend()中做依赖收集。而Dep 就是整个 getter 依赖收集的核心。 Dep 定义在 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的一些相关实现,它的定义在 src/core/observer/watcher.js 中:
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
if (isRenderWatcher) {
vm._watcher = this
}
// 记录了所有watcher,包括计算属性和侦听器
vm._watchers.push(this)
// options
if (options) {
this.deep = !!options.deep
this.user = !!options.user
// 是否延迟执行,比如计算属性的watcher是需要延迟执行的
this.lazy = !!options.lazy
this.sync = !!options.sync
// 触发beforeUpdate
this.before = options.before
} else {
this.deep = this.user = this.lazy = this.sync = false
}
// 计算属性和侦听器会传入noop
this.cb = cb
this.id = ++uid // uid for batching
// 当前watcher是否是活动watcher
this.active = true
this.dirty = this.lazy // for lazy 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 {
// expOrFn是字符串时,如 watch:{'person.age':function()...}
// parsePath(expOrFn)返回一个函数获取person.age的值
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
)
}
}
// 若是计算属性,则将lazy设置为true
// 先不调用get,计算属性对应的方法是在render的过程中调用
this.value = this.lazy
? undefined
: this.get()
}
/**
* Evaluate the getter, and re-collect dependencies.
*/
get() {
// 组件有嵌套的时候,先渲染内部的组件,所以先把父组件对应的watcher保存起来
pushTarget(this)
let value
const vm = this.vm
try {
// 若是renderWatcher,调用updateComponent
// 若是用户watcher,获取属性的值
// 而且是对属性进行层级访问,触发 data 中目标属性的 get 方法, 触发属性对应的 dep.depend 方法, 进行依赖收集
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
// 深度监听
// 当data的属性发生变动时,触发属性的set方法
if (this.deep) {
traverse(value)
}
// 弹出当前watcher
popTarget()
// 移除dep subs中的该watcher,移除watcher中记录的dep
this.cleanupDeps()
}
return value
}
/**
* Add a dependency to this directive.
*/
// watcher中添加dep的原因是?
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
}
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
//
update() {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
// 渲染watcher只会执行这个
queueWatcher(this)
}
}
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
run() {
// 当前watcher是否存活
if (this.active) {
// 触发该watcher的get方法,获取该属性的值
// 如果是渲染watcher,this.get()没有返回值,value为undefined
const value = this.get()
// 新值和旧值(旧值通过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
// 用户watcher
if (this.user) {
const info = `callback for watcher "${this.expression}"`
// 处理用户传入的回调异常情况
invokeWithErrorHandling(this.cb, this.vm, [value, oldValue], this.vm, info)
} else {
this.cb.call(this.vm, value, oldValue)
}
}
}
}
/**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*/
evaluate() {
this.value = this.get()
this.dirty = false
}
/**
* Depend on all deps collected by this watcher.
*/
depend() {
let i = this.deps.length
while (i--) {
this.deps[i].depend()
}
}
/**
* Remove self from all dependencies' subscriber list.
*/
teardown() {
if (this.active) {
// remove self from vm's watcher list
// this is a somewhat expensive operation so we skip it
// if the vm is being destroyed.
if (!this.vm._isBeingDestroyed) {
remove(this.vm._watchers, this)
}
let i = this.deps.length
while (i--) {
this.deps[i].removeSub(this)
}
this.active = false
}
}
}watcher类中这四个属性与dep类有关:
this.deps = []
this.newDeps = []
this.depIds = new Set()
this.newDepIds = new Set()不过现在并不知道为什么这里需要两个Deps?暂时放一边,先关注一下是如何触发的收集依赖的。
在mount一节中有分析过挂载的核心是先实例化一个渲染Watcher(观察者模式),在它的回调函数中会调用 updateComponent 方法,在此方法中调用 vm.render 方法先生成虚拟 Node,最终调用 vm.update 更新DOM,构建dom tree。
new Watcher(vm, updateComponent, noop, {
before() {
if (vm._isMounted && !vm._isDestroyed) {
callHook(vm, 'beforeUpdate')
}
}
}, true /* isRenderWatcher */)在实例化 watcher 的过程中,会触发get方法,
value = this.getter.call(vm, vm)在这里this.getter对应的就是updateComponent函数,它会先生成vnode,在生成vnode的过程中会对vm上的数据访问,那时会触发数据对象的getter,进而触发dep.depend()方法,
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),收集watcher将它们个存储在dep的subs属性中,收集的目的就是为了后续数据更改时去通知依赖做更改。
cleanupDeps?
收集完依赖后,有一步操作是cleanupDeps 为什么要进行这一步 数据变化时触发了什么? 调试依赖收集和派发更新
Q: 为什么要执行 cleanupDeps?
派发更新
当我们修改了数据,会触发数据的setter方法,最后将派发更新,执行dep.notify()。
set: function reactiveSetter(newVal) {
// 使用预定义的getter获取旧值value
const value = getter ? getter.call(obj) : val
/* eslint-disable no-self-compare */
// 若新值等于旧值或者新值旧值为nan时不执行,因为nan不等于自身
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
}
// 若新值是对象,观察子对象并返回子的observer对象
childOb = !shallow && observe(newVal)
// 派发更新
dep.notify()
}notify()
class Dep {
// ...
notify () {
// stabilize the subscriber list first
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}notify就是Dep类的一个实例方法,里面的逻辑就是遍历subs数组中(也就是收集的依赖)进行update()更新。与之对应的,update()就是Watcher类对应的实例方法。
class 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)
}
}
}一般组件更新的话触发queueWatcher(),也就是渲染watcher。 queueWatcher定义在src/core/observer/scheduler.js中。
export function queueWatcher(watcher: Watcher) {
const id = watcher.id
// 防止watcher被重复处理
if (has[id] == null) {
has[id] = true
// 当前队列没有被处理的情况下
if (!flushing) {
queue.push(watcher)
} else {
// 否则当前queue正在被处理
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
let i = queue.length - 1
// index表示当前处理到的queue的索引,i>index就表示当前queue还没有被处理完
// 找到watcher待插入的位置
while (i > index && queue[i].id > watcher.id) {
i--
}
// 找到位置后,将watcher插入到i后面的一个位置
queue.splice(i + 1, 0, watcher)
}
// queue the flush
// 判断当前队列是否被执行
if (!waiting) {
waiting = true
if (process.env.NODE_ENV !== 'production' && !config.async) {
// 调用所有watcher,并调用watcher的run方法
flushSchedulerQueue()
return
}
// 调用nexttick,在下一个tick执行flushSchedulerQueue
nextTick(flushSchedulerQueue)
}
}
}Vue 在做派发更新的时候的一个优化的点,它并不会每次数据改变都触发 watcher 的回调,而是把这些 watcher 先添加到一个队列里,然后在 nextTick 后执行 flushSchedulerQueue。 通过对waiting的判断,保证nexttick只执行一次,将在下一个tick执行flushSchedulerQueue。
let flushing = false
let index = 0
/**
* Flush both queues and run the watchers.
*/
function flushSchedulerQueue () {
flushing = true
let watcher, id
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
queue.sort((a, b) => a.id - b.id)
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
watcher = queue[index]
if (watcher.before) {
watcher.before()
}
id = watcher.id
has[id] = null
watcher.run()
// in dev build, check and stop circular updates.
if (process.env.NODE_ENV !== 'production' && has[id] != null) {
circular[id] = (circular[id] || 0) + 1
if (circular[id] > MAX_UPDATE_COUNT) {
warn(
'You may have an infinite update loop ' + (
watcher.user
? `in watcher with expression "${watcher.expression}"`
: `in a component render function.`
),
watcher.vm
)
break
}
}
}
// keep copies of post queues before resetting state
const activatedQueue = activatedChildren.slice()
const updatedQueue = queue.slice()
resetSchedulerState()
// call component updated and activated hooks
callActivatedHooks(activatedQueue)
callUpdatedHooks(updatedQueue)
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush')
}
}Q:为什么队列需要先排序? 1.组件的更新由父到子;因为父组件的创建过程是先于子的,所以 watcher 的创建也是先父后子,执行顺序也应该保持先父后子。 2.用户的自定义 watcher 要优先于渲染 watcher 执行;因为用户自定义 watcher 是在渲染 watcher 之前创建的。 3.如果一个组件在父组件的 watcher 执行期间被销毁,那么它对应的 watcher 执行都可以被跳过,所以父组件的 watcher 应该先执行。
排序后进行遍历,但是queue的长度是可变的。? 在对 queue 排序后,接着就是要对它做遍历,拿到对应的 watcher,执行 watcher.run()。这里需要注意一个细节,在遍历的时候每次都会对 queue.length 求值,因为在 watcher.run() 的时候,很可能用户会再次添加新的 watcher,这样会再次执行到 queueWatcher,如下:
export function queueWatcher (watcher: Watcher) {
const id = watcher.id
if (has[id] == null) {
has[id] = true
if (!flushing) {
queue.push(watcher)
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
let i = queue.length - 1
while (i > index && queue[i].id > watcher.id) {
i--
}
queue.splice(i + 1, 0, watcher)
}
// ...
}
}watcher.run()
class Watcher {
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
run () {
if (this.active) {
this.getAndInvoke(this.cb)
}
}
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)
}
}
}
}run 函数实际上就是执行 this.getAndInvoke 方法,并传入 watcher 的回调函数。getAndInvoke 函数逻辑也很简单,先通过 this.get() 得到它当前的值,然后做判断,如果满足新旧值不等、新值是对象类型、deep 模式任何一个条件,则执行 watcher 的回调,注意回调函数执行的时候会把第一个和第二个参数传入新值 value 和旧值 oldValue,这就是当我们添加自定义 watcher 的时候能在回调函数的参数中拿到新旧值的原因。
那么对于渲染 watcher 而言,它在执行 this.get() 方法求值的时候,会执行 getter 方法:
updateComponent = () => {
vm._update(vm._render(), hydrating)
}当我们去修改组件相关的响应式数据的时候,会触发组件重新渲染的原因(执行了回调),接着就会重新执行 patch 的过程。
重点是调试一下依赖收集和派发更新的过程。
问题
动态添加或删除属性是响应式的吗?
var vm = new Vue({
data:{
a:1
}
})
// vm.b 是非响应的
vm.b = 2vue2官方文档中明确提到了这样不会触发setter,继而触发视图更新,必须手动触发set和delete方法。
set和delete源码