响应式原理

284 阅读1分钟

响应式原理

1、理解响应式原理是什么?

2、响应式原理中响应函数的封装

const reactFns = [];
function(fn){
  reactFns.push(fn);
}

3、Depand依赖收集类的封装

class Depand{
  constructor(){
    let reactFns = [];
  }
  addFns(fn){
    this.reactFns.push(fn);
  }
  notify(){
    this.reactFns.forEach(fn => {
      fn();
    })
  }
}

4、自动监听类的封装

const objProxy = new Proxy(obj,{
  get:function(target,key,receiver){
    return Reflect.get(target,key,receiver);
  },
  set:function(target,key,newValue,receiver){
    Relect.set(target,key,newValue,receiver);
    depand.notify();
  }
});
把所有obj的依赖均修改为objProxy的依赖

5、依赖收集的管理

const targetMap = new WeakMap();
function getDepand(target,key){
  let map = targetMap.get(target);
  if(!map){
    map = new Map();
    targetMap.set(target);
  }
  let depand = map.get(key);
  if(!depand){
    depand = new Depand();
    map.set.(key);
  }
  return depand;
}
...
// 监听对象的属性变量:Proxy(vue3)/Object.defineProperty(vue2)
const objProxy = new Proxy(obj, {
  get: function (target, key, receiver) {
    return Reflect.get(target, key, receiver);
  },
  set: function (target, key, newValue, receiver) {
    Reflect.set(target, key, newValue, receiver);
    // 自动监听 
    // depand.notify();
    const depand = getDepand(target, key);
    depand.notify();
  }
});

6、正确收集依赖

let activeReactiveFn = null;
functionn watchFn(fn){
  activeReactiveFn = fn;
  fn();
  activeReactiveFn = null;
}
...
const objProxy = new Proxy(obj, {
  get: function (target, key, receiver) {
    // 根据target.key获取对应的depand
    const depand = getDepand(target,key);
    // 给depand对象中添加响应函数
    depand.addDepand(activeReactiveFn);
    return Reflect.get(target, key, receiver);
  },
  set: function (target, key, newValue, receiver) {
    Reflect.set(target, key, newValue, receiver);
    // 自动监听 
    // depand.notify();
    const depand = getDepand(target, key);
    depand.notify();
  }
});

7、对depand优化

1、给对象depend的addDepend方法更换为depend方法
  1、直接获取到自由变量
2、更换存储依赖函数的数组结构为Set结构,防止重复收集依赖函数

对对象的响应式操作

封装reactive函数 1、new Proxy();Vue3 2、Object.defineProperty();Vue2