Vue

256 阅读4分钟

Vue 响应式原理模拟

Vue2

数据响应式

  • 数据模型仅仅是普通的就是对象,而当我们修改数据时,视图会进行更新,避免了繁琐的 DOM 操作,提高开发效率

  • 双向绑定

    • 数据改变,视图改变;视图改变,数据也随之改变
    • 我们可以使用 v-model 在表单元素上创建双向数据绑定
  • 数据驱动是 Vue 最独特的特性之一

    • 开发过程中仅需要关注数据本身,不需要关新数据是如何渲染到视图

数据响应式的核心原理 当你把一个普通的 js 对象传入 Vue 实例做为 data 选项,Vue 将遍历次对象所以的属性,并使用 Object.defineProperty 把这些属性全部转换为 getter、setter。

改变一个参数

// 模拟 Vue 中的data选项
let data = {
  msg: "hello",
};
// 模拟Vue的实例
let vm = {};

//数据劫持: 当访问或者设置vm中的成员的时候,做一些干预操作
Object.defineProperty(vm, "msg", {
  //可枚举(可遍历)
  enumerable: true,
  //可配置(可以使用delete删除,可以通过defineProperty 重新定义 )
  configurable: true,
  // 当获取值的时候执行
  get() {
    console.log("get", data.msg);
    return data.msg
  },
  set(newValue){
    console.log('set:'newValue)
    if(newValue ===data.msg){
      return
    }
    data.msg = newValue
    //数据更改,更新Dom的值
    document.querySelectot('#app').textContent = data.msg
  }
});

多个

// 模拟 Vue 中的data选项
let data = {
  msg: "hello",
  count: 10,
};
// 模拟Vue的实例
let vm = {};
proxyData(data);

function proxyData(data) {
  Object.keys(data).forEach((key) => {
    //数据劫持: 当访问或者设置vm中的成员的时候,做一些干预操作
    Object.defineProperty(vm, key, {
      //可枚举(可遍历)
      enumerable: true,
      //可配置(可以使用delete删除,可以通过defineProperty 重新定义 )
      configurable: true,
      // 当获取值的时候执行
      get() {
        console.log("get", data[key]);
        return data[key]
      },
      set(newValue){
        console.log('set:'newValue)
        if(newValue ===data[key]){
          return
        }
        data[key] = newValue
        //数据更改,更新Dom的值
        document.querySelectot('#app').textContent = data[key]
      }
    });
  });
}

Vue3

let vm = new Proxy(data, {
  get(target, key) {
    console.log("get,key:", key, target[key)
    return target[key]
  },
  set(target,key,newValue){
    // console.log('set,key:',key,newValue)
    if(target[key] === newValue){
      return
    }
    target[key] = newValue;
    document.querySelectot('#app').textContent = data[key]

  }
});

订阅发布模式(Vue 的自定义事件):由统一调度中心调用,因此发布者和订阅者不需要知道对方的存在

  • 发布订阅模式
    • 订阅者
    • 发布者
    • 信号中心
//Vue自定义事件
let vm = new Vue();
//{'click':[fn1,fn2],'change':[fn]} 以对象的形式注册事件
// 注册事件(订阅消息)
VM.$on("dataChange", () => {
  console.log("dataChange");
});
// 注册事件(订阅消息)
VM.$on("dataChange", () => {
  console.log("dataChange1");
});
//触发事件(发布消息)
vm.$emit("dataChange");
//事件触发器
class EventEmitter {
  constructor() {
    //{'click':[fn1,fn2],'change':[fn]} 以对象的形式注册事件
    this.subs = Object.create(none);
  }
  //注册事件
  $on(eventType, handler) {
    this.subs[eventType] = this.subs[eventType] || [];
    this.subs[eventType].push(handler);
  }
  //触发事件
  $emit(eventType, handler) {
    if (this.subs[eventType]) {
      this.subs[eventType].forEach((handler) => {
        handler();
      });
    }
  }
}

观察者模式:是由具体目标调度,比如当前事件触发,Dep 就会去调用观察者的方法,所以观察者模式的订阅于发布之间是存在依赖的

  • 观察者(订阅者) --Watcher
    • update():当事件发生时,具体要做的事情
  • 目标(发布者)--Dep
    • subs 数组:存储所有的观察者
    • addSub():添加观察者
    • notify():当时间发生,调用所有观察者的 update()方法
  • 没有事件中心
// 发布者-目标
class Dep {
  constructor() {
    //记录所有的订阅者
    this.subs = [];
  }
  addSub(sub) {
    if (sub && sub.update) {
      this.subs.push(sub);
    }
  }
  notify() {
    this.subs.forEach((sub) => {
      sub.update();
    });
  }
}
// 订阅者-观察者
class Watcher {
  update() {
    console.log("update");
  }
}

//测试
let dep = new Dep();
let watcher = new Watcher();
dep.addSub(watcher);
dep.notify(watcher);

模拟 Vue 响应式原理模拟

整体分析 Vue -> observer (数据劫持) -> dep (发布者) -> watcher 观察者 -> compiler (解析指令) -> Vue

  • 功能

    • 负责接收初始化的参数(选项)
    • 负责把 data 中的属性注入到 Vue 实例,转换成 getter/setter
    • 负责调用 observers 监听 data 中所有属性变化
    • 负责调用 complier 解析指令/差值表达式
  • 结构

  • vue

    • $options
    • $el
    • $data
    • _proxyData()
    • Oberver
      • walk(data)
      • defineReactive(data,key,value)
//vue.js
class Vue {
  constructor(options) {
    // 1.通过属性保存选项的数据
    this.$options = options || {};
    this.$data = options.data || {};
    this.$el =
      typeof options.el === "string"
        ? document.querySekector(options.el)
        : options.el;
    // 2.把data中的成员传化成getter和setter,注入到vue实例中
    this._proxyData(this.$data);
    // 3.调用observer对象,监听数据的变化
    new Observer(this.$data);
    // 4.调用compiler对象,解析指令和差值表达式
    new Compiler(this);
  }
  _proxyData(data) {
    Object.keys(data).forEach((key) => {
      Object.defineProperty(this, key, {
        emumerable: true,
        configurable: true,
        get() {
          return data[key];
        },
        set(newValue) {
          if (newValue === data[key]) {
            return;
          }
          data[key] = newValue;
        },
      });
    });
  }
}
  • Oberver
    • walk(data)
    • defineReactive(data,key,value)
class Observer {
  constructor(data) {
    this.walk(data);
  }
  walk(data) {
    // 1.判断data是否是对象
    if (!data || typeof data !== "object") {
      return;
    }
    // 2.遍历data对象的所有属性
    Object.keys(data).forEach((key) => {
      this.defineReactive(data, key, data[key]);
    });
  }
  defineReactive(obj, key, val) {
    // 如果val是对象,吧Val内部的属性转化成响应式数据
    this.walk(val)
    let dep = new Dep()
    const self = this
    Object.defineProperty(obj, key, {
      emumerable:true,
      configurable:true,
      get(){
        Deo.target && dep.addSub(Dep.target)
        return val
      }
      set(newValue){
        if(newValue === val){
          return
        }
        val = newValue
        self.walk(newValue)
        // 发送通知
        dep.notify()
      }
    })
  }
}
  • Compiler
    • 功能
      • 复制编译模板,解析指令/差值表达式
      • 复制页面的首次渲染
      • 当数据变化猴重新渲染视图
    • 结构
      • Compiler
        • el
        • vm
        • compile(el)
        • compileElement(node)
        • complieText(node)
        • isDirective(attrName)
        • isTextNode(node)
        • isElementNode(node)
class Compiler {
  constructor(vm) {
    this.el = vm.$el;
    this.vm = vm;
    this.compiler(this.el);
  }
  // 编译模板,处理文本节点和元素节点
  compile(el) {
    const childNodes = el.childNodes;
    Array.from(childNodes).forEach((node) => {
      if (this.isTextNode(node)) {
        // 处理文本节点
        this.complieText(node);
      } else if (isElementNode(node)) {
        // 处理元素节点
        this.compileElement(node);
      }
      //判断node节点,是否有子节点,如果有子节点,要递归调用compile
      if (node.childNodes && node.childNodes.length) {
        this.compile(node);
      }
    });
  }
  //编译元素节点,处理指令
  compileElement(node) {
    // 遍历所有的属性节点
    Array.from(node.attributes).forEach((attr) => {
      // 判断是否是指令
      let attrName = attr.name;
      // 判断是否是指令
      if (this.isDirective(attrName)) {
        // v-text -->text
        attrName = attrName.substr(2);
        let key = attr.value;
        this.update(node, key, attrName);
      }
    });
  }
  update(node, key, attrName) {
    let updateFn = this[attrName + "Updater"];
    updateFn && updateFn.call(this, node, this.vm[key], key);
  }
  //v-text
  textUpdater(node, value, key) {
    node.textContent = value;
    new Watcher(this.vm, key, (newVlue) => {
      node.textContent = newValue;
    });
  }
  // v-model
  modelUpdater(node, value, key) {
    node.value = value;
    new Watcher(this.vm, key, (newVlue) => {
      node.value = newValue;
    });
    node.addEventListener('input',()=>{
      this.vm[key] = node.value
    })
  }
  //编译文本节点,处理差值表达式
  complieText(node) {
    //差值表达式 {{ msg }}
    let reg = /\{\{(.+?)\}\}/;
    let value = node.textContent;
    if (reg.test(value)) {
      let key = RegExp.$1.trim();
      node.textContent = value.replace(reg, this.vm[key]);
      //创建watcher对象,当数据变化更新视图
      new Watcher(this.vm, key, (newVlue) => {
        node.textContent = newValue;
      });
    }
  }
  //判断节点是否是指令
  isDirective(attrName) {
    return attrName.startWith("v-");
  }
  // 判断节点是否是文本节点
  isTextNode(node) {
    return node.nodeType === 3;
  }
  // 判断节点是否是元素节点
  isElementNode(node) {
    return node.nodeType === 1;
  }
}
  • Dep
    • subs
    • addSub(sub)
    • notify()
class Dep {
  constructor(){
    //储存所有观察者
    this.subs = []
  }
  //添加观察者
  addSub(sub){
    if(sub&&sub.updata){
      this.subs.push(sub)
    })
  }
  //发布观察者
  notify(){
    this.subs.forEach(sub=>{
      sub.update()
    })
  }
}
  • watcher
    • vm
    • key
    • cb
    • oldValue
    • update()
class Watcher {
  constructor(vm, key, cb) {
    this.vm = vm;
    // data中属性名称
    this.key = key;
    //回调函数负责更新视图
    this.cb = cb;

    //把watcher对象记录到Dep类的静态属性target
    Dep.target = this;
    // 触发get方法,在get方法中会调用addsub
    this.oldValue = vm[key];
  }
  //当数据发生变化的时候更新视图
  update() {
    let newValue = this.vm[this.key];
    if (this.oldValue === newValue) {
      return;
    }
    this.cb(newValue);
  }
}