vue数据响应式原理 - 依赖收集
什么是依赖?
- vue1.x,细粒度依赖,用到数据的 DOM 都是依赖;
- Vue2.x,中等粒度依赖,用到数据的 组件 是依赖;
- 在 getter 中收集依赖,在 setter 中触发依赖
把依赖收集的代码封装成一个Dep类,它专门用来管理依赖,每个Observer的实例,成员中都有一个Dep的实例;
Watcher 是一个中介, 数据发生变化时通过 Watcher 中转,通知组件
Dep 类和 Watcher 类
- 依赖就是 Watcher。只有 Watcher 触发的 getter 才会收集依赖,哪个 Watcher 触发了 getter,就把哪个 Watcher 收集到 Dep中。
- Dep 使用发布订阅模式,当数据发生变化时,会循环依赖列表,把所有的 Watcher 都通知一遍。
- 代码实现的巧妙之处:Watcher 把自己设置到全局的一个指定位置,然后读取数据,因为读取了数据,所以会触发这个数据的 getter。在getter 中就能得到当前正则读取数据的 Watcher ,并把这个 Watcher 收集到 Dep 中。
Dep 的位置:每个对象下面都有 __ob__ 原型,是 Observer 对象,里面有个 dep 属性
以下图片来自:https://juejin.cn/post/6932659815424458760
类似于 买家 (Watcher) 在淘宝 (Dep) 订阅一个商品 (数据) 的预售,订阅 (get) 时,淘宝 (Dep) 会登记用户信息(收集依赖),在商品开始卖时(数据更新),通知买家 (dep.notify() 一下,然后触发 watcher 中的update(),再触发callback()方法)
下面是所有代码:
文件目录结构:
index.js
import observe from './observe';
import Watcher from './Watcher';
let obj = {
a: {
m: {
n: {
e: {
f: 5
}
}
}
},
b: 3,
g: [1,2,3]
};
observe(obj);
new Watcher(obj, 'a.m.n', (val) => {
console.log('⭐⭐⭐⭐',val);
});
obj.a.m.n = 88;
console.log(obj);
observe.js
import Observer from './Observer.js';
// 创建 observe 函数,注意函数的名字没有r
export default function observe (value) {
// 函数只为对象服务
if (typeof value !== 'object') return;
// 定义 ob
let ob;
if (typeof value.__ob__ !== 'undefined') {
ob = value.__ob__;
} else {
ob = new Observer(value);
}
return ob;
}
Observer.js
import { def } from './utils.js';
import defineReactive from './defineReactive.js';
import { arrayMethods } from './array.js';
import observe from './observe.js';
import Dep from './Dep.js';
export default class Observer {
constructor(value) {
// 每一个 Observe 的实例身上,都有一个 Dep 实例
this.dep = new Dep();
// 给实例(构造函数中的this表示实例)添加了__ob__属性
def(value, '__ob__', this, false);
// Observer类的目的是:将一个正常的 object 转换为每个层级的属性都是响应式(可以被侦测的)的 object
// 检查是数组还是对象
if (Array.isArray(value)) {
// 如果是数组,就要将这个数组的原型指向 arrayMethods
Object.setPrototypeOf(value, arrayMethods);
this.observeArray(value);
} else {
this.walk(value);
}
}
// 遍历
walk(value) {
for (let key in value) {
defineReactive(value, key);
}
}
// 数组的特殊遍历
observeArray(arr) {
for(let i = 0; i < arr.length; i++) {
// 逐项进行 observe
observe(arr[i]);
}
}
}
defineReactive.js
import Dep from './Dep';
import observe from './observe';
export default function defineReactive(data, key, val) {
const dep = new Dep();
if (arguments.length == 2) {
val = data[key];
}
// 子元素要进行 observe, 至此形成了递归,
// 这个递归不是函数自己调用自己
let childOb = observe(val);
Object.defineProperty(data, key, {
// 可枚举
emuerable: true,
// 可以被配置,比如可以被 delete
configurable: true,
get() {
console.log(`正在访问${key}属性`, val);
// 如果现在处于依赖收集阶段
if (Dep.target) {
dep.depend();
if (childOb) {
childOb.dep.depend();
}
}
return val;
},
set(newValue) {
console.log(`正在改变${key}属性`, newValue);
if (val === newValue) { return };
val = newValue;
// 当设置了新值,新值也要 observe
childOb = observe(newValue);
// 发布订阅模式
dep.notify();
}
})
}
Dep.js
var uid = 0;
export default class Dep {
constructor() {
console.log('我是Dep类');
this.id = uid++;
// 用数组存储自己的订阅者, subs 是 subscribes 订阅者的意思。
// 这个数组里面放的是 Watcher 的实例
this.subs = [];
}
// 添加订阅
addSub(sub) {
this.subs.push(sub);
}
// 添加依赖
depend() {
// Dep.target 就是一个自己指定的全局的位置,你用window.target也想
// 只要是全局唯一,没有歧义就行
if (Dep.target) {
this.addSub(Dep.target);
}
}
// 通知更新
notify() {
console.log('我是 notify');
// 浅克隆一份
const subs = this.subs.slice();
// 遍历
for (let i = 0; i < subs.length; i++) {
subs[i].update();
}
}
}
Watcher.js
import Dep from "./Dep";
let uid = 0;
export default class Watcher {
constructor(target, expression, callback) {
console.log('我是 Watcher 类');
this.id = uid++;
this.target = target;
this.getter = parsePath(expression);
this.callback = callback;
this.value = this.get();
}
update() {
this.getAndInvoke(this.callback);
}
get() {
// 进入依赖收集阶段,让全局的 Dep.target 设置为 Watcher 本身
Dep.target = this;
const obj = this.target;
let value;
// 只要能找,就一直找
try {
value = this.getter(obj);
} finally {
console.log('没找着');
Dep.target = null;
}
return value;
}
getAndInvoke(cb) {
// 得到并且唤起
const value = this.get();
if (value !== this.value || typeof value == 'object') {
const oldValue = this.value;
cb.call(this.target, value, oldValue);
}
}
}
function parsePath(str) {
let segments = str.split('.');
return (obj) => {
for (let i = 0; i < segments.length; i++) {
if (!obj) return;
obj = obj[segments[i]];
}
return obj;
}
}
utils.js
export const def = function(obj, key, value, emurable) {
Object.defineProperty(obj, key, {
value,
emurable,
writable: true,
configurable: true
})
}
array.js
import { def } from './utils';
const arrayPrototype = Array.prototype;
// 以 Array.prototype 为原型创建 arrayMethods 对象
export const arrayMethods = Object.create(arrayPrototype);
// 要被改写的七个方法
const methodsNeedChange = [
'push',
'pop',
'shift',
'unshift',
'sort',
'reverse',
'splice',
];
methodsNeedChange.forEach(item => {
// 备份原来的方法,原有功能不能被剥夺
const original = arrayPrototype[item];
// 定义新的方法
def(arrayMethods, item, function() {
// 恢复原来的功能,this代表调用该方法的数组,arguments就是push的内容
const result = original.apply(this, arguments);
// 将类数组转换为数组
const args = [...arguments];
// 把这个数组身上的__ob__取出来,__ob__已经被添加了
// 为什么已经被添加了?
// 因为数组肯定不是最高层,比如 obj.g 属性是数组,obj不能是数组,
// 第一次遍历 obj 这个对象的第一层的时候,已经给 g 属性添加了 __ob__属性。
const ob = this.__ob__;
// 有三种方法 push、unshift、splice 能够插入新项,现在要把插入的新项也变为 observe 的
let inserted = [];
switch(item) {
case 'push':
case 'unshift':
// push(新项) unshift(插入的新项)
inserted = arguments;
break;
case 'splice':
// slice(下标,数量,插入的新项)
inserted = args.slice(2);
break;
}
// 让插入的新项也变成响应的
if (inserted) {
ob.observeArray(inserted);
}
console.log('啦啦啦');
ob.dep.notify();
return result;
}, false);
});
生活是痛苦的白天,死亡是凉爽的夜晚。