02模仿格式類似Vue初探究

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <!-- 寫模板 -->
  <div id="app">
    <div>
      <p>{{name}}</p>
      <p>{{age}}</p>
    </div>
    <div>
      <p>{{name}}</p>
    </div>
  </div>
</body>
<script>
  // 1. 拿到模板
  let rzz = /\{\{(.+?)\}\}/g;
  //遞歸
  function recursionDOM(temple, data) {
    let $childNodes = temple.childNodes;
    let $data = data;
    for (let i = 0; i < $childNodes.length; i++) {
      if ($childNodes[i].nodeType === 3) {
        // 文本節點, 可以判斷裏面是否有 {{}} 插值
        let txt = $childNodes[i].nodeValue;
        txt = txt.replace(rzz, (_, g) => {
          let key = g.trim();
          return data[key];
        });
        $childNodes[i].nodeValue = txt;
      } else if ($childNodes[i].nodeType === 1) {
        recursionDOM($childNodes[i], $data);
      }
    }
  }

  function LZVue(option) {
    //先將數據複製過來
    this._data = option.data;
    this._el = option.el;
    this._templeDOM = document.querySelector(this._el);
    this._parentNode = this._templeDOM.parentNode;
    // 渲染工作
    this.render()
  }
  LZVue.prototype.render = function () {
    this.recursionDOM();
  }

  LZVue.prototype.recursionDOM = function () {
    let realDOMtree = this._templeDOM.cloneNode(true)
    recursionDOM(realDOMtree, this._data);
    this.update(realDOMtree)
  }
  /** 將 DOM 的元素 放到頁面中 */
  LZVue.prototype.update = function (real) {
    this._parentNode.replaceChild(real, document.querySelector('#app'));
  }
  let app = new LZVue({
    data: {
      name: "張山",
      age: "15"
    },
    el: "#app"
  });
</script>

</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章