vue2 的响应式核心原理代码 其实就只有几个模块
1. 代理 Object.defineProperty
2.依赖收集dep,收集所有监听页面数据的watcher实例
3. 监听页面数据实例 watcher
4.观察者 Observer ,实现数据劫持
5.编译模块 Compiler
下面来简单实现一下各个模块代码,新建index.js文件
1.首先简单实现Vue类,和基本代理功能
export class Vue{
constructor(options = {}){
this.$options = options
this.$el = typeof options.el ==='string' ? document.querySelector(options.el):options.el
this.$data = options.data
this.$methods = options.methods
this.proxy(this.$data)
//observer 拦截 this.$data
new Observer(this.$data)
new Compiler(this)
}
//代理一下,this.$data.xx=>this.xx
proxy(data){
Object.keys(data).forEach(key=>{
Object.defineProperty(this,key,{
enumerable:true,
configurable:true,
get(){
return data[key]
},
set(newValue){
console.log(newValue)
if(data[key] === newValue || (Number.isNaN(data[key]) && Number.isNaN(newValue)) ) return
data[key] = newValue
}
})
})
}
}
2.Dep依赖收集模块,收集所有watcher实例
class Dep{
constructor(){
this.deps = new Set()
}
//手机副作用代码,count
add(dep){
console.log("dep")
console.log(dep)
if(dep && dep.update) this.deps.add(dep)
}
notify
最低0.47元/天 解锁文章
279

被折叠的 条评论
为什么被折叠?



