Vue双向数据绑定 - 浅谈

Vue的双向数据绑定的原理(v-model的原理:value+oninput)
* View -> Model : 事件
* Model -> View :getter&setter

* vue在实例化时会遍历data中所有属性,通过Object.defineProperty()方法把它们设置为存储器属性(getter & setter),并写入Vue实例

以下使用原生JS实现vue实例化时将data的属性设置为存储器属性,并写入Vue实例

  function Vue(option) {
        this.$el = document.querySelector(option.el);
        let data = this.$data = option.data;
        this.proxyData(data);
    }
    Vue.prototype.proxyData = function(data) {
        var arr = [];
        for (var key in data) {
            var obj = [];
            obj[0] = key
            obj[1] = data[key];
            arr.push(obj)
        }
        arr.forEach((item, idx) => {
            Object.defineProperty(this, item[0], {
                configurable: true,
                enumerable: true,
                get: function() {
                    return data[item[0]]
                },
                set: function(val) {
                    data[item[0]] = val
                }
            })
        })
    }


    let vm = new Vue({
        el: "#app",
        data: {
            name: "lemon",
            age: 18
        }
    });
    console.log(vm)

  

猜你喜欢

转载自www.cnblogs.com/dukeshao/p/10765084.html