zoukankan      html  css  js  c++  java
  • 手写一个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;
    })
  • 相关阅读:
    bzoj2467 [中山市选2010]生成树
    hdu4489 The King’s Ups and Downs
    hdu4489 The King’s Ups and Downs
    Tyvj1014(区间dp)
    Tyvj1014(区间dp)
    Tyvj1013
    Tyvj1013
    Tyvj1009
    22.引用指针
    21.引用指针
  • 原文地址:https://www.cnblogs.com/onesea/p/13294092.html
Copyright © 2011-2022 走看看