仿写Vue(二)构造函数

2、构造函数MyVue

本身动手实践,就会更加深入的理解


此次的主题:实现构造函数 MyVue。
在上一篇文章中,遗留了如下一些问题:javascript

  • 尚未整合成构造函数
  • 没法替换形如 name.firstName 的层级属性
  • 没有使用虚拟DOM

今天,主要解决一件事,实现构造函数 MyVue,并在其原型上添加 render, compiler, update 这三个方法。
html

0一、实现构造函数 MyVue

(首先声明,实际的Vue会有所不一样)vue

  • 构造函数只能用 new 调用
  • 获取到元素和数据
  • 调用 render 函数
function MyVue(options) {

      if (!this instanceof MyVue) {
        console.error('Vue is a constructor and should be called with the `new` keyword')
      }

      // 内部数据用 _ 开头,只读数据用 $ 开头
      this._data = options.data;
      this._el = options.el;

      // 准备模板与父节点
      this.$el = this._template = document.querySelector(this._el);
      this._parent = this._template.parentNode;
      // 开始渲染
      this.render();
    }

0二、render 函数

其次,在 MyVue 的原型上添加 render 函数,目前尚未杂七杂八的生命周期函数,因此只需编译便可~java

MyVue.prototype.render = function () {
      this.compiler();
    }

0三、compiler函数

最后,在 MyVue 的原型上添加 compiler 函数,内部调用以前写好的编译函数。git

/** 编译,获得真正的DOM */
    MyVue.prototype.compiler = function () {
      let newDOM = this._template.cloneNode(true);
      compiler(newDOM, this._data); // 这个函数在上一章中写到
      this._parent.replaceChild(newDOM, this._template);
    }

0四、效果展现

html内代码以下github

<div id="root">
    <p>{{name}}</p>
    <p>{{message}}</p>
    <p>{{name}} -- {{message}}</p>
  </div>
  
    let app = new MyVue({
      el: '#root',
      data: {
        name: 'romeo',
        message: 'handsome but bad guy',
      }
    })

效果图:



更多源代码请看个人 github
欢迎关注个人公众号,查看更多系列文章~
公众号二维码.pngweb

相关文章
相关标签/搜索