仿写Vue的{{}}语法

 仿写Vue的{{}}语法思路:

1.获取dom元素中的innerText内容,判断是否有{{}}符号

2.正则匹配{{}}内容,获取{{}}中的内容A

3.通过内容A和定义的对象data内容,去递归查找匹配内容B

4.把内容B重新赋值给dom元素innerText

 以下完整代码

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h1>{{aaa.aab.aac}}</h1>
  <h2>{{bbb.bbc}}</h2>
  <h3>{{ccc}}</h3>
  <h4>我</h4>
  <script>
    let data = {
      aaa: { aab: { aac: '观音大士' } },
      bbb: { bbc: '黑熊精' },
      ccc: '红孩儿',
    }
    let doms = document.body.children

    // 2.把处理后的文字重新赋值给dom元素
    function getValue(data, str, key) {
      // 3.如果data里面也是对象
      if (str.includes('.')) {
        const index = str.indexOf('.')
        const dataChlid = data[str.substr(0, index)]
        const pre = str.substr(0, index + 1)
        const after = str.substr(index + 1)
        getValue(dataChlid, after, key)
      } else {
        doms[key].innerHTML = data[str]
      }
    }
    // 1.读取dom元素,利用正则获取dom元素中{{}}中的内容
    window.justMounted = () => {
      // 获取body下的children
      for (const key in doms) {
        // 确定不是script标签
        if (doms[key].localName !== 'script') {
          const text = doms[key].innerText // {{ aaa }}
          // 正则匹配且存在{{}}
          const regex = /\{\{([^{}]+)\}\}/;
          let match = text?.match(regex)
          // 如果真实DOM内容存在{{}}
          if (match) {
            const innerText = match[1]
            // 把获取到的文字交给以下方法处理
            getValue(data, innerText, key)
          }
        }
      }
    }
    window.justMounted()
    // 如果{{}}}报错,边界判断,

  </script>
</body>

</html>

做个记录,如有不足,欢迎指正。

积跬步,至千里。感谢前进路上的每个小困难,冲!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值