配合ppt食用更佳ppt
实现的最终目标
const demo = new Vue({
data: {
text: "before",
},
// 对应的template 为 <div><span>{
{text}}</span></div>
render(h){
return h('div', {}, [
h('span', {}, [this.__toString__(this.text)])
])
}
})
setTimeout(function(){
demo.text = "after"
}, 3000)
对应的虚拟DOM会从
<div><span>before</span></div>
变成
<div><span>after</span></div>
第一步,监听data下边的所有属性,转换为响应式
思路
- 当data下的某个属性变化时,如何触发相应的函数?
方案:ES5中新添加了一个方法:Object.defineProperty,通过这个方法,可以自定义getter
和setter
函数,那么在获取对象属性或者设置对象属性时就能够执行相应的回调函数
代码如下:
class Vue {
constructor(options) {
this.$options = options
this._data = options.data
observer(options.data, this._update.bind(this))
this._update()
}
_update(){
this.$options.render()
}
}
function observer(obj, cb) {
Object.keys(obj).forEach((key) => {
defineReactive(obj, key, obj[key], cb)
})
}
function defineReactive(obj, key, val, cb) {
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: () => {
console.log('你访问了' + key)
return val
},
set: newVal => {
if (newVal === val)
return
console.log('你设置了' + key)
console.log('新的' + key + ' = ' + newVal)
val = newVal
cb()
}
})
}
var demo1 = new Vue({
el: '#demo',
data: {
text: "before"
},
render(){
console.log("我要render了")
}
})
- 引发了第二个问题,如果
data
中的属性是一个对象还能触发我们的回掉函数么?比如说下边的demo