vue 数据绑定

https://www.cnblogs.com/libo0125ok/p/8038073.html


    let data = {price: 5, count: 10, res: 50}
    let target = null
    class Observer {
        constructor () {
            this.array = []
        }
        subscribe() {
            if( target && !this.array.includes(target)) {
                this.array.push(target)
            }
        }
        notify() {
            this.array.forEach(sub => sub())
        }
    }

    Object.keys(data).forEach(key => {
        let internalValue = data[key]
        const obs = new Observer()
        Object.defineProperty(data, key, {
            get() {
                obs.subscribe()
                console.log('get:' +internalValue)
                return internalValue
            },
            set(val) {
                internalValue = val
                console.log('set:'+ val)
                obs.notify()
            }
        })
    });

    
    function watcher(func) {
        target = func
        target()
        target = null
    }

    watcher(() => {
        data.res = data.price * data.count
    })

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。