• 手写一个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;
    })
  • 相关阅读:
    OA项目之分页
    OA项目之弹出层中再弹出层
    OA项目之导入
    OA项目之导出
    git使用6步走
    配置 Docker 镜像站
    Taro随笔
    byte(C# 参考)
    MySQL 笔记
    HTTP 错误代码
  • 原文地址:https://www.cnblogs.com/onesea/p/13294092.html
Copyright © 2020-2023  润新知