vue源码----mvvm代码注释

2021/5/5 20:27:04

本文主要是介绍vue源码----mvvm代码注释,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

function MVVM(options) {
    //增加一个$options属性然后把传递过来的东西存起来
    this.$options = options;
    this.$options.beforeCreate && this.$options.beforeCreate();
    //在实例上新增_data 保存传来的data数据
    var data = this._data = this.$options.data;
    //保存this 为了之后使用this的时候保证this指向的正确性
    var me = this;
    //通过Object.keys取到data中的数据
    Object.keys(data).forEach(function(key) {
        // 遍历调用_proxy方法
        me._proxy(key);
    });
    this.$options.created && this.$options.created();
    //结合订阅发布为data中的数据进行劫持 
    observe(data, this);
    //增加模版解析
    this.$compile = new Compile(options.el || document.body, this)
}

MVVM.prototype = {
    $watch: function(key, cb, options) {
        new Watcher(this, key, cb);
    },
    _proxy: function(key) {//实现数据代理
        var me = this;//暂存this 保证this的指向正确 this(vm) 
        //通过defineProperty方法在实例上新增所有与data中属性所对应属性,并且为该属性添加get和set方法
        Object.defineProperty(me, key, {
            configurable: false,
            enumerable: true,
            get: function proxyGetter() {
                //实现了vm代理data中数据的读操作
                return me._data[key];
            },
            set: function proxySetter(newVal) {//vm.name = "bb"
                //实现了vm代理data中数据的写操作
                me._data[key] = newVal;
            }
        });
    }
};


这篇关于vue源码----mvvm代码注释的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程