virtualvm2 观察者模式

<template>
    <div id="app">
        <input type="text" v-model='msg'>
        <div>
            <p>{{msg}}</p>
        </div>
    </div>
</template>

<script>

class Observer{
    static _observe(obj){
        for(var key in obj){
        //遍历obj对象

            var value =obj[key];
            if(typeof value ==='object'){
                //如果值还是对象,则遍历处理
                Observer._observe(value);
            }
            console.log("========def" ,key);
            Object.defineProperty(obj, key, {
                    enumerable: true,
                    configurable: true,
                    set: function (newValue) {
                        if( value !== newValue ) {
                            var value = newValue;
                            console.log('setter:' + newValue);
                        }
                    },
                    get: function () {
                        console.log('getter:' +value);
                        return value;
                    }
                });

        }
    }
}

class VM{
    constructor(options){
        this.$options = options;
        this._obverse(this.$options.data);
        return  Object.assign({data:this.$options.data}, this.$options.methods );
    }
    _obverse(data) {
        return  Observer._observe(data);
    }
   
}
var vm = new VM({
    el: '#app',
    data: {
        msg:'hello'
    },
    methods: {
        hello:function(){
           console.log("hello");
        }
    }
})



vm.data.msg = "wwww"
var x = vm.data.msg;
vm.hello();

</script>

猜你喜欢

转载自www.cnblogs.com/mlzrq/p/11164884.html