Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于vue2.0 的实现源码剖析(一) #11

Open
hawx1993 opened this issue May 4, 2017 · 2 comments
Open

关于vue2.0 的实现源码剖析(一) #11

hawx1993 opened this issue May 4, 2017 · 2 comments
Labels

Comments

@hawx1993
Copy link
Owner

hawx1993 commented May 4, 2017

Vue.js双向绑定的实现原理

实现数据绑定的做法有大致如下几种:

  • 发布者-订阅者模式(backbone.js)

  • 脏值检查(angular.js)

  • 数据劫持(vue.js)

数据劫持: vue.js 采用数据劫持的方式,结合发布者-订阅者模式,通过Object.defineProperty()来劫持各个属性的setter,getter以监听属性的变动,在数据变动时发布消息给订阅者,触发相应的监听回调:

var obj = { };

// 为obj定义一个名为 say 的访问器属性
Object.defineProperty(obj, "say", {
         get: function () {console.log('get方法被调用了')},

         set: function (val) {console.log('set方法被调用了,参数是'+val)}
})

obj.say // 可以像普通属性一样读取访问器属性,get方法被调用了
obj.say = 'hello vue';//set方法被调用了,参数是hello vue

实现一个极简的MVVM:

<body>
        <input type="text" name="" value="" id='J_vueInput'>
        <p id="J_span"></span>
    </body>
    <script type="text/javascript">
        var obj = {};
        Object.defineProperty(obj,'say',{
            set: function (val) {
                document.getElementById('J_vueInput').value = val;
                document.getElementById('J_span').innerHTML = val;
            }
        })
        document.addEventListener('keyup',function (e) {
            obj.say = e.target.value;
        })
    </script>

image

@hawx1993 hawx1993 added the vue label Nov 21, 2017
@ishuiz
Copy link

ishuiz commented Dec 8, 2017

<p id="J_span"></span>

标签

@zhangxing0716
Copy link

hahahaha 不应该是'

<span id="J_span"></span>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants