仿寫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

相關文章
相關標籤/搜索