[vue][原理]利用vue响应式原理实现一个时钟

关于vue2.x响应式原理核心内容可以查看这里

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>reactive timer</title>
</head>
<body>
<div id="app"></div>
<script>
// 数据响应式:
// Object.defineProperty()
const app = document.getElementById('app')
const obj = {}
function defineReactive(obj, key, val) {
  Object.defineProperty(obj, key, {
    get() {
      console.log('get', key)
      return val
    },
    set(newVal) {
      if (newVal !== val) {
        console.log('set', key)
        val = newVal
        update()
      }
    }
  })
}

defineReactive(obj, 'foo', '')

function update() {
// dom 操作
  app.innerText = obj.foo.toLocaleTimeString()
}

setInterval(() => {
  obj.foo = new Date()
}, 1000)
</script>
</body>
</html>
posted @ 2020-05-14 12:04  丹哥不是哥  阅读(617)  评论(0编辑  收藏  举报