1. 程式人生 > 實用技巧 >手寫一個vue雙向繫結的過程

手寫一個vue雙向繫結的過程

  1. 通過Object.defineProperty()來進行資料劫持
    demo.html
<body>
   <div id="app">
       {{message}}
   </div>
 <script>
     var vm =  new NanLan({
         el: "#app",
         data: {
             message: 'hello vue',
             age: "29",
             hobby: "skating",
             occupation: "programmer"
         },
         template: "<div>{{message}}</div>"
     })
     vm.message = 'hello xiaojuxiaoju';
     console.log(vm.message);
 </script>
</body>

demo.js

(function (root, factory) {
    root.NanLan = factory()
})(this, function () {
    function NanLan(options) {
        this.$options = options || {};
        var data = this._data = options.data; // 例項裡面的data的所有屬性
        var _this = this;
        // 代理
        Object.keys(data).forEach(function (key) {
            _this._proxy(key);
        })
    }
    NanLan.prototype._proxy = function (key) {
        Object.defineProperty(this, key, {
            get: function () {
                return this._data[key]; // 這裡輸出的是 hello xiaojuxiaoju
            },
            set: function (newValue) {
                this._data[key] = newValue; // 將NanLan例項的值賦值給data裡面與之對應的值
            }
        });
    }
    return NanLan;
})