关于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>