vue 響應性程式碼demo

howhy發表於2024-04-13
<!DOCTYPE html>
<html lang="en">

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

<body>
  <!-- <input type="text" inputmode="email" accesskey="b" tabindex="1"> -->
  <h3 id="firstname"></h3>
  <h3 id="lastname"></h3>
  <h3 id="age"></h3>
  <script>
    let user = {
      name: '大海一',
      age: 12
    }
    function getFristName() {
      document.getElementById('firstname').innerText = user.name[0]
    }
    function getLastName() {
      document.getElementById('lastname').innerText = user.name.slice(1)
    }
    function getAge() {
      document.getElementById('age').innerText = user.age
    }
    function observe(obj) {
      for (let key in obj) {
        let initVal = obj[key]
        let keyFuns = []
        Object.defineProperty(obj, key, {
          get() {
            if (window.__fun && !keyFuns.includes(window.__fun)) {
              keyFuns.push(window.__fun)
            }
            return initVal
          },
          set(val) {
            initVal = val
            keyFuns.forEach(fun => fun())
          }
        })
      }
    }
    observe(user)
    function runFun(fun) {
      window.__fun = fun
      fun()
      window.__fun = null
    }
    runFun(getFristName)
    runFun(getLastName)
    runFun(getAge)
  </script>
</body>

</html>

相關文章