美文网首页VUE学习
手写简易版本Vue源码

手写简易版本Vue源码

作者: myth小艾 | 来源:发表于2020-02-25 15:33 被阅读0次

前言
1.此版本是vue1.0的版本,watcher的监听粒度为页面级(出现多少引用数据就有多少个whater,2.0会小到组件级别)
2.主要是为了了解依赖收集的过程

简版Vue流程

核心思想:(你可以把下面的代码看完后在回头品一下)

  1. 一个Dep对应一个Key,多个{{}}对应多个Watcher 统一由Dep管理
  2. 初始化时,通过编译分析界面节点,做编译操作,页面初始化也完成了,另外根据页面上的表达式产生对应的Watcher
  3. 每创建一个Watcher实例会把Water实例通过赋值操作赋值给Dep.target静态变量,然后访问执行defineReactive中的getdep.addWatcher(Dep.target);,这时候数据已经与Dep产生联系。
  4. 当页面数据发生更改的时候,触发set方法,这个时候执行Dep.notify()方法 通知内部属性watchers数组实例执行update()方法 执行对应的更新回调操作。

目标

  1. {{}}插值表达式的解析
  2. a-model指令的实现

只为说明发布订阅

测试文件

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <input type="text" a-model="name" />
      <p>{{name}}</p>
      <p>{{name}}</p>
    </div>
  </body>
</html>
<script src="Dep.js"></script>
<script src="Watcher.js"></script>
<script src="AVue.js"></script>
<script src="Compiler.js"></script>
<script>
  //一个key对应一个dep  多个插值表达式
  let app = new AVue({
    el: "#app",
    data: {
      name: "测试",
      a: 1,
    }
  });
  console.log(app);
</script>

注意这里是name.a 是深层次的获取和修改
1.Dep.js依赖搜集管理类 一个key对应一个dep
2.Watcher.js数据监听类 一个Dep对应多个Watcher 页面多个{{}} v-text 值输出对应一个Watcher事例(vue2.0以上是组件级别一个组件对应一个Watcher)
3.AVue.js核心文件啦~
4.Compiler.js dom级别的编译器,正常情况是虚拟dom render的时候做关联

AVue.js

class AVue {
  constructor(options) {
    this.$options = options;
    this.$data = options.data;
    //这个是多余的  目的是为了测试一个{{}}对应一个wahter
    this.deps = [];
    this.observe(this.$data);
    new Compiler(options.el, this);
  }

  //数据响应
  observe(Value) {
    if (!Value || typeof Value !== "object") {
      return;
    }
    Object.keys(Value).forEach(key => {
      this.defineReactive(Value, key, Value[key]);
      //代理
      this.proxyData(key);
    });
  }

  //数据响应  val作为闭包 存取都是用临时变量 防止出现死循环
  defineReactive(obj, key, val) {
    //递归
    this.observe(val);
    //做依赖收集  为什么会写在这里呢?写在这里实例不会多创建,也是对应的一个key对应一个实例
    let dep = new Dep();
    //测试添加
    this.deps.push(dep);
    //get和set是独立的回调函数 val值作为闭包临时变量共享
    Object.defineProperty(obj, key, {
      get() {
        //添加到Dep瞬时调用收集到
        console.log("get" + key);
        if (Dep.target) dep.addWatcher(Dep.target);
        return val;
      },
      set(newVal) {
        console.log("set" + key);
        if (val === newVal) return;
        val = newVal;
        //广播通知更新操作 发布
        dep.notify();
      }
    });
  }

  //代理data
  proxyData(key) {
    // 需要给vue实例定义属性
    Object.defineProperty(this, key, {
      get() {
        return this.$data[key];
      },
      set(newVal) {
        this.$data[key] = newVal;
      }
    });
  }
}

我把重点的地方在强调一遍~
1.defineReactive方法哪里 val作为闭包 存取都是用临时变量,如果都是改变的原本值,那么会造成死循环
2.defineReactive的get方法 if (Dep.target) dep.addWatcher(Dep.target); 手动调用get时添加到dep实例上,这里的dep也是因为闭包的关系 关系对应一个key对应一个实例,每次调用会dep都是这个闭包内的实例
3.defineReactive的set方法dep.notify 每次设置 通知dep内的所有watcher执行更新回调,更新对应的更新方法,跟新页面数据。

Dep.js

//创建Dep
//和data中的每一个key对应起来,主要负责管理相关watcher
class Dep {
  constructor() {
    this.watchers = [];
  }
  addWatcher(watcher) {
    this.watchers.push(watcher);
  }
  notify() {
    this.watchers.forEach(watcher => watcher.update());
  }
}

Dep里面比较简单 作用就是为了能够统一管理和调用watcher.update()更新操作

Watcher.js

//Watcher:负责创建data中的key 和更新函数的映射
class Watcher {
  constructor(vm, key, cb) {
    this.$vm = vm;
    this.$key = key;
    this.$cb = cb;
    //关键:
    //1.把当前的watcher实例附加到Dep的静态属性上(这里的Dep.target相当于一个临时变量)
    //2.然后访问下属性触发执行get方法添加到dep里面
    Dep.target = this;
    this.$vm[this.$key]; //触发依赖收集
    Dep.target = null; //置空
  }
  update() {
   this.$cb && this.$cb.call(this.$vm, this.$vm[this.$key]);
  }
}

1.把当前的watcher实例附加到Dep的静态属性上(这里的Dep.target相当于一个临时变量)
2.然后访问下属性触发执行get方法添加到dep实例的watchers属性里面

Compiler.js

class Compiler {
  constructor(el, vm) {
    this.$vm = vm;
    this.el = document.querySelector(el);
    this.compile(this.el);
  }
  compile(node) {
    let nodes = node.childNodes;
    Array.from(nodes).forEach(node => {
      //判断节点类型
      if (this.isElement(node)) {
        //是元素标签
        this.compileElement(node);
      } else if (this.isInter(node)) {
        //是插值文本{{}}
        this.compileText(node);
      }
      this.compile(node);
    });
  }
  isElement(node) {
    return node.nodeType === 1;
  }
  isInter(node) {
    return node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent);
  }
  compileText(node) {
    this.update(node, RegExp.$1, "text");
  }

  compileElement(node) {
    //获取属性
    let nodeAttrs = node.attributes;
    Array.from(nodeAttrs).forEach(attr => {
      const attrName = attr.name;
      const value = attr.value;
      //指令|事件
      if (this.isDirective(attrName)) {
        //截取指令名字
        const dir = attrName.slice(2);
        //执行相应指令的函数
        this[dir] && this[dir](node, value);
      }
    });
  }
  isDirective(attr) {
    return ~attr.indexOf("a-");
  }

  model(node, key) {
    node.value = this.$vm[key];
    node.addEventListener("input", e => {
      this.$vm[key] = e.target.value
    });
  }

  //update函数  负责更新dom,同时创建watcher实例在两者之间产生联系
  update(node, key, dir) {
    //初始运行
    const updaterFn = this[dir + "Updater"];
    
    updaterFn && updaterFn(node, this.$vm[key]);
    
    //修改时的更新埋点 订阅触发
    new Watcher(this.$vm, key, function(value) {
      updaterFn && updaterFn(node, value);
    });
  }

  textUpdater(node, value) {
    node.textContent = value;
  }

}
编译拆解步骤

1.这里是用的实际dom来代替虚拟dom的编译过程,拆解页面元素分析如上图
2.多个方法拆分是为了复用,RegExp.$1静态方法是读取正则运行test方法后的静态属性获取匹配分组的数据。这里拿到的是key值

测试结果

一个Dep对应一个Key,一个页面插值表达式对应一个watcher

后续拓展

data数据如何多级层次渲染?
事件,其他指令,组件等 后续在来研究~
代码地址内有答案 包括上述代码
代码地址:https://gitee.com/biglove/vue-study.git

相关文章

网友评论

    本文标题:手写简易版本Vue源码

    本文链接:https://www.haomeiwen.com/subject/kmzqqhtx.html