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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值