VUE2 / 数据双向绑定原理图解+代码

数据双向绑定原理图

Observer类:

class Observer{
    constructor(data){
        this.observe(data)
    }
    observe(data){
        if(data && typeof data == "object" ){
            Object.keys(data).forEach(key=>{
            	//递归添加getter和setter
                this.defineReactive(data,key,data[key])
            })
        }
    }
    defineReactive(data,key,value){
        this.observe(value);
        let dep = new Dep()
        Object.defineProperty(data,key,{
            enumerable:true,// 可枚举
            configurable:false, // 不能再define
            get(){
                // 订阅数据时,往Dep中添加观察者
                console.log(key)
                Dep.target && dep.addSub(Dep.target) && console.log(Dep.target)
                return value
            },
            set:(newVal)=>{
                this.observe(newVal)
                // console.log("设置")
                if(value !== newVal){
                    value = newVal
                }
                // 告诉Dep通知变化
                dep.notify()
            }
        })
    }
}

Dep类

class Dep{
    constructor(){
        this.subs = []
    }
    // 收集观察者
    addSub(watcher){
        this.subs.push(watcher)
    }
    // 通知变化
    notify(){
        this.subs.forEach(w=>w.update())
    }
}

Watcher类

class Watcher{
    constructor(vm,expr,cb){
        this.vm = vm
        this.expr = expr
        this.cb = cb
        this.oldVal = this.getOldVal()
    }
    getOldVal(){
        Dep.target = this
        let oldVal = compileUtil.getval(this.expr,this.vm)
        Dep.target = null
        return oldVal
    }
    update(){
        let newVal = compileUtil.getval(this.expr,this.vm)
        if(newVal !== this.oldVal){
            this.cb(newVal)
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值