vue2.0源码 Object.defineProperty实现数据响应
vue设计的初衷: 1.将视图view的状态和行为抽象化,使得UI和业务逻辑分开 2.mvvm:model=>view=>viewmodel
数据响应式原理 数据变更能够在视图中,就是数据响应式。vue2中利用Object.defineProperty()实现实时变化检测 1、数据响应式:监听数据变化并在视图中更新
defineReactive实现数据响应式在html的应用实例 xx.html
<div id="app"></div> <script> 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, newVal) val = newVal updated() } } }) } // 测试 const obj = {} defineReactive(obj, foo, ) setInterval(() => { obj.foo = new Date().toLocaleTimeString() }, 1000) // 更新函数 function updated() { app.innerHTML = obj.foo } </script>
最终可以看到时间视图不断在更新