实现简易Vue2

class Vue {
  constructor(options) {
    if (typeof options !== "object") {
      throw new TypeError("Vue 所传配置项必须为对象!");
    }
    this.$options = options || {};
    this.$data = options.data || {};
    this.$el = options.el;
    // 代理数据
    this.proxyData(this.$data);
    // 处理响应式数据
    new Observe(this.$data);
    // 处理视图
    if (this.$el) new Compiler(this.$el, this);
  }
  proxyData(data) {
    Object.keys(data).forEach((key) => {
      Object.defineProperty(this, key, {
        enumerable: true,
        configurable: true,
        get() {
          return data[key];
        },
        set(newVal) {
          if (newVal !== data[key]) data[key] = newVal;
        },
      });
    });
  }
}

class Observe {
  constructor(data) {
    this.observe(data);
  }
  observe(data) {
    if (data && typeof data === "object") {
      Object.keys(data).forEach((key) => {
        this.deifneReactive(data, key, data[key]);
      });
    }
  }
  deifneReactive(data, key, value) {
    // 首先递归深层嵌套结构数据
    this.observe(value);
    const that = this;
    let dep = new Dep(); // 创建收集者
    Object.defineProperty(data, key, {
      enumerable: true,
      configurable: true,
      get() {
        // 如果存在当前的Dep.target 就添加
        Dep.target && dep.addSub(Dep.target);
        return value;
      },
      set(newVal) {
        that.observe(newVal);
        if (newVal !== value) value = newVal;
        // 发送通知
        dep.notify();
      },
    });
  }
}
class Compiler {
  static compileUtil = {
    getVal(key, vm) {
      return key.split(".").reduce((data, current) => {
        return data[current];
      }, vm.$data);
    },
    setVal(key, vm, inputVal) {
      let total = "vm";
      if (key.split(".").length === 1) vm[key] = inputVal;
      else {
        key.split(".").forEach((k) => (total += `['${k}']`));
        total += "=" + `${"inputVal"}`;
        eval(total);
      }
    },
    text(node, key, vm) {
      let value;
      if (/\{\{(.+?)\}\}/.test(key)) {
        value = key.replace(/\{\{(.+?)\}\}/, (...args) => {
          new Watcher(vm, args[1], (newVal) => {
            this.updater.textUpdater(node, newVal);
          });
          return this.getVal(args[1], vm);
        });
      } else {
        value = this.getVal(key, vm);
      }
      this.updater.textUpdater(node, value);
    },
    html(node, key, vm) {
      let value = this.getVal(key, vm);
      new Watcher(vm, key, (newVal) => {
        this.updater.htmlUpdater(node, newVal);
      });
      this.updater.htmlUpdater(node, value);
    },
    model(node, key, vm) {
      let value = this.getVal(key, vm);
      new Watcher(vm, key, (newVal) => {
        this.updater.modelUpdater(node, newVal);
      });
      node.addEventListener("input", (e) => {
        this.setVal(key, vm, e.target.value);
      });
      this.updater.modelUpdater(node, value);
    },
    on(node, key, vm, eventName) {
      let fn = vm.$options.methods && vm.$options[key];
      node.addEventListener(
        eventName,
        function (ev) {
          fn.call(vm, ev); // 改变fn函数内部的this,并传递事件对象event
        },
        false
      );
    },
    bind(node, key, vm, attrName) {
      // 处理v-bind指令
      node[attrName] = vm.$data[key];
    },
    updater: {
      // 保存所有更新页面视图的方法的对象
      textUpdater(node, value) {
        node.textContent = value;
      },
      htmlUpdater(node, value) {
        node.innerHTML = value;
      },
      modelUpdater(node, value) {
        node.value = value;
      },
    },
  };
  constructor(el, vm) {
    this.el = this.isElementType(el) ? el : document.querySelector(el);
    this.vm = vm;
    // 创建文档碎片
    const fragment = this.creatFragment(this.el);
    // 处理节点
    this.compile(fragment);
    // 添加元素节点
    this.el.appendChild(fragment);
  }
  compile(node) {
    // 取出所有元素节点
    [...node.childNodes].forEach((child) => {
      if (this.isElementType(child)) {
        // 元素节点
        this.creatElement(child);
      } else {
        // 文本节点
        this.creatText(child);
      }
      if (child.childNodes && child.childNodes.length) this.compile(child);
    });
  }
  creatElement(child) {
    // 取出元素节点所有的属性
    const { compileUtil } = Compiler;
    [...child.attributes].forEach((attr) => {
      const { name, value } = attr;
      if (this.isReactive(name)) {
        const direcTive = name.split("-")[1];
        const [direcName, eventName] = direcTive.split(":");
        compileUtil[direcName](child, value, this.vm, eventName);
        node.removeAttribute("v-" + direcTive);
      } else if (name.indexOf("@") > -1) {
        // 不是v-开头的指令
        const directive = name.split("@")[1];
        compileUtil["on"](node, value, this.vm, directive);
        node.removeAttribute("@" + directive);
      }
    });
  }
  creatText(node) {
    const { compileUtil } = Compiler;
    let content = node.textContent;
    if (/\{\{(.+?)\}\}/.test(content)) {
      compileUtil["text"](node, content, this.vm);
    }
  }
  isReactive(node) {
    // 判断是否以v-开头的属性
    return node.startsWith("v-");
  }
  creatFragment(el) {
    const f = document.createDocumentFragment();
    let firstChild;
    while ((firstChild = el.firstChild)) f.appendChild(firstChild);
    return f;
  }
  isElementType(node) {
    return node.nodeType === 1;
  }
}

class Dep {
  constructor() {
    this.subs = [];
  }
  addSub(sub) {
    this.subs.push(sub);
  }
  notify() {
    this.subs.forEach((k) => k.update());
  }
}
class Watcher {
  constructor(vm, key, callback = (value) => {}) {
    this.vm = vm;
    this.key = key;
    this.callback = callback;
    this.oldVal = this.getOldVal();
  }
  getOldVal() {
    // 把当前观察者this挂载到Dep的target属性上
    Dep.target = this;
    const oldVal = Compiler.compileUtil.getVal(this.key, this.vm);
    Dep.target = null;
    return oldVal;
  }
  update() {
    const newVal = Compiler.compileUtil.getVal(this.key, this.vm);
    if (newVal !== this.oldVal) this.callback(newVal);
  }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容