vue 数据绑定

作者: zzz1t1 | 来源:发表于2019-07-01 17:12 被阅读0次

    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
        })
    
    

    相关文章

      网友评论

        本文标题:vue 数据绑定

        本文链接:https://www.haomeiwen.com/subject/oalncctx.html