vue2.x双向数据绑定原理

1 vue双向数据绑定深入理解

当你把一个普通的JavaScript对象传入Vue实例作为data选项,Vue将遍历此对象的所有Property,并使用Object.defineProperty把这些Property全部转为getter/setter。Object.defineProperty是ES5中一个无法shim的特性,这也是Vue不支持IE8以及更低版本浏览器的原因。
这些getter/setter对用户来说是不可见的,但是在内部它们让Vue能够追踪依赖,在property被访问和修改时通知变更。

2双向数据绑定原理代码实现

//操作了一个属性
<body>
    <div id="app"></div>
    <script>
        let data={
            msg:'hello'
        }
        let vm={}
        Object.defineProperty(vm,"msg",{
            enumerable:true,//可枚举
            configurable:true, //可配置,
            get(){
                console.log('get',data.msg);
            },
            set(newValue){
                console.log('set',newValue);
                if(newValue===data.msg){
                    return;
                }
                data.msg=newValue;
                document.querySelector("#app").textContent=data.msg
            }
        })
        vm.msg="你好哈哈哈";
    </script>   
</body>
//操作了多个属性
<body>
    <div id="app"></div>
    <!-- <script>
        let data={
            msg:'hello'
        }
        let vm={}
        Object.defineProperty(vm,"msg",{
            enumerable:true,//可枚举
            configurable:true, //可配置,
            get(){
                console.log('get',data.msg);
            },
            set(newValue){
                console.log('set',newValue);
                if(newValue===data.msg){
                    return;
                }
                data.msg=newValue;
                document.querySelector("#app").textContent=data.msg
            }
        })
        vm.msg="你好哈哈哈";

    </script> -->
     <script>
         //data中有多个属性
         let data={
             msg:'hello',
             count:10
         }
         let vm={}
         proxyData(data);
         function proxyData(data){
         Object.keys(data).forEach((key)=>{
             Object.defineProperty(vm,key,{
                 enumerable:true,
                 configurable:true,
                 get(){
                     console.log('get',key,data[key]);
                     return data[key];
                 },
                 set(newValue){
                     console.log('set',key,newValue);
                     if(data[key]===newValue){
                         return;
                     }
                     data[key]=newValue;
                     document.querySelector("#app").textContent= data[key]
                 }
             })

         })

         }
         vm.msg="今天星期三";
         console.log(vm.msg);
     </script>
</body>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值