文章首发于:github.com/USTB-musion…javascript
Vue.js是一款MVVM框架,核心思想是数据驱动视图,数据模型仅仅是普通的 JavaScript 对象。而当修改它们时,视图会进行更新。实现这些的核心就是“响应式系统”。java
咱们在开发过程当中可能会存在这样的疑问:react
响应式系统核心的代码定义在src/core/observer中:git
这部分的代码是很是多的,为了让你们对响应式系统先有一个印象,我在这里先实现一个简易版的响应式系统,麻雀虽小五脏俱全,能够结合开头那张图的下半部分来分析,写上注释方便你们理解。github
/** * Dep是数据和Watcher之间的桥梁,主要实现了如下两个功能: * 1.用 addSub 方法能够在目前的 Dep 对象中增长一个 Watcher 的订阅操做; * 2.用 notify 方法通知目前 Dep 对象的 subs 中的全部 Watcher 对象触发更新操做。 */
class Dep {
constructor () {
// 用来存放Watcher对象的数组
this.subs = [];
}
addSub (sub) {
// 往subs中添加Watcher对象
this.subs.push(sub);
}
// 通知全部Watcher对象更新视图
notify () {
this.subs.forEach((sub) => {
sub.update();
})
}
}
// 观察者对象
class Watcher {
constructor () {
// Dep.target表示当前全局正在计算的Watcher(当前的Watcher对象),在get中会用到
Dep.target = this;
}
// 更新视图
update () {
console.log("视图更新啦");
}
}
Dep.target = null;
class Vue {
// Vue构造类
constructor(options) {
this._data = options.data;
this.observer(this._data);
// 实例化Watcher观察者对象,这时候Dep.target会指向这个Watcher对象
new Watcher();
console.log('render', this._data.message);
}
// 对Object.defineProperty进行封装,给对象动态添加setter和getter
defineReactive (obj, key, val) {
const dep = new Dep();
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
// 往dep中添加Dep.target(当前正在进行的Watcher对象)
dep.addSub(Dep.target);
return val;
},
set: function reactiveSetter (newVal) {
if (newVal === val) return;
// 在set的时候通知dep的notify方法来通知全部的Wacther对象更新视图
dep.notify();
}
});
}
// 对传进来的对象进行遍历执行defineReactive
observer (value) {
if (!value || (typeof value !== 'object')) {
return;
}
Object.keys(value).forEach((key) => {
this.defineReactive(value, key, value[key]);
});
}
}
let obj = new Vue({
el: "#app",
data: {
message: 'test'
}
})
obj._data.message = 'update'
复制代码
执行以上代码,打印出来的信息为:express
render test
视图更新啦
复制代码
下面结合Vue.js源码来分析它的流程:api
咱们都知道响应式的核心是利用来ES5的Object.defineProperty()方法,这也是Vue.js不支持IE9一下的缘由,并且如今也没有什么好的补丁来修复这个问题。具体的能够参考MDN文档。这是它的使用方法:数组
/* obj: 目标对象 prop: 须要操做的目标对象的属性名 descriptor: 描述符 return value 传入对象 */
Object.defineProperty(obj, prop, descriptor)
复制代码
其中descriptor有两个很是核心的属性:get和set。在咱们访问一个属性的时候会触发getter方法,当咱们对一个属性作修改的时候会触发setter方法。当一个对象拥有来getter方法和setter方法,咱们能够称这个对象为响应式对象。markdown
Vue其实是一个用Function实现的类,定义在src/core/instance/index.js中: 当用new关键字来实例化Vue时,会执行_init方法,定义在src/core/instance/init.js中,关键代码以下图:app
在这当中调用来initState()方法,咱们来看一下initState()方法干了什么,定义在src/core/instance/state.js中,关键代码以下图:
能够看出来,initState方法主要是对props,methods,data,computed和watcher等属性作了初始化操做。在这当中调用来initData方法,来看一下initData方法干了什么,定义在src/core/instance/state.js,关键代码以下图:
其实这段代码主要作了两件事,一是将_data上面的数据代理到vm上,另外一件是经过observe将全部数据变成observable。值得注意的是data中key不能和props和methods中的key冲突,不然会产生warning。
接下来看Observer的定义,在/src/core/observer/index.js中:
/** * 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它的做用就是给对象的属性添加getter和setter,用来依赖收集和派发更新。walk方法就是把传进来的对象的属性遍历进行defineReactive绑定,observeArray方法就是把传进来的数组遍历进行observe。
接下来看一下defineReative方法,定义在src/core/observer/index.js中:
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()
}
})
复制代码
对象的子对象递归进行observe并返回子节点的Observer对象:
childOb = !shallow && observe(val)
复制代码
若是存在当前的Watcher对象,对其进行依赖收集,并对其子对象进行依赖收集,若是是数组,则对数组进行依赖收集,若是数组的子成员仍是数组,则对其遍历:
if (Dep.target) {
dep.depend()
if (childOb) {
childOb.dep.depend()
if (Array.isArray(value)) {
dependArray(value)
}
}
}
复制代码
执行set方法的时候,新的值须要observe,保证新的值是响应式的:
childOb = !shallow && observe(newVal)
复制代码
dep对象会执行notify方法通知全部的Watcher观察者对象:
dep.notify()
复制代码
Dep是Watcher和数据之间的桥梁,Dep.target表示全局正在计算的Watcher。来看一下依赖收集器Dep的定义,在/src/core/observer/dep.js中:
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)
}
// 依赖收集,当存在Dep.target的时候添加Watcher观察者对象
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
// 收集完依赖以后,将Dep.target设置为null,防止继续收集依赖
复制代码
Watcher是一个观察者对象,依赖收集之后Watcher对象会被保存在Deps中,数据变更的时候会由Deps通知Watcher实例。定义在/src/core/observer/watcher.js中:
/** * 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
}
/** * Subscriber interface. * Will be called when a dependency changes. */
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)
}
}
/** * 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)
}
}
}
/** * 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
}
/** * Depend on this watcher. Only for computed property watchers. */
depend () {
if (this.dep && Dep.target) {
this.dep.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
}
}
}
复制代码
响应式系统的原理基本梳理完了,如今再回过头来看这幅图的下半部分是否是清晰来呢。
你能够关注个人公众号「慕晨同窗」,鹅厂码农,日常记录一些鸡毛蒜皮的点滴,技术,生活,感悟,一块儿成长。