vue源码—03依赖收集与追踪

 

 

 

 

 

js 

// new KVUE({data:{...}})

class KVue {
    constructor(options) {
        this.$options = options;

        // 数据响应化
        this.$data = options.data;
        this.observe(this.$data)

        //模拟一下watcher的创建
        new Watcher();
        this.$data.test;
        new Watcher();
        this.$data.foo.bar;

    }
    observe(value) {
        if (!value || typeof value !== 'object') {
            return
        }

        // 遍历该对象
        Object.keys(value).forEach(key => {
            // 定义响应化
            this.defineReactive(value, key, value[key])
        })
    }

    // 数据的响应化
    defineReactive(obj, key, val) {
        this.observe(val);//解决数据嵌套

        // 初始化dep
        const dep = new Dep();

        Object.defineProperty(obj, key, {
            get() {
                Dep.target && dep.addDep(Dep.target)
                return val;
            },
            set(newVal) {
                if (newVal === val) {
                    return;
                }
                val = newVal;
                dep.notify();
                // console.log(`${key}属性更新了:${val}`);
            }
        })
    }
}

// Dep 用来管理watcher
class Dep {
    constructor() {
        // 这里存放若干依赖(watcher)
        this.deps = [];
    }

    addDep(dep) {
        this.deps.push(dep)
    }

    notify() {
        this.deps.forEach(dep=>dep.update())
    }
}

// watcher
class Watcher {
    constructor(){
        // 将当前watcher实例指定到Dep静态属性target
        Dep.target = this
    }
    update() {
        console.log('属性更新了')
    }
}

html

<html>

<head>
    <title>definedproperty</title>
</head>

<body>
    <script src="./kvue.js"></script>
    <script>
        const app = new KVue({
            data: {
                test: "I am test",
                foo: {
                    bar: "bar"
                }
            }
        });
        app.$data.test = "hello, jjsun";
        app.$data.foo.bar = "oh my bar";
    </script>
</body>

</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值