vue3 源码解析学习笔记--- vue2.0 和vue3.0实现双向绑定的简单比较

vue 2.0

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="yingaxiang" content="width=device-width, initial-scale=1.0">
    <title>vue2.x数据双向绑定</title>
</head>
<body>
    <div>
        <input type="text" id="input">
        <span id="text"></span>
    </div>
</body>
</html>
<script>
    var obj = {};
    Object.defineProperty(obj, 'prop', {
        get: function () {
            return val;
        },
        set: function (newVal) {
            val = newVal;
            document.getElementById('text').innerHTML = val;
        }
    });
    document.addEventListener('keyup', function (e) {
        obj.prop = e.target.value;
    });
</script>

vue 3.0

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="yingaxiang" content="width=device-width, initial-scale=1.0">
    <title>vue3.0数据双向绑定</title>
</head>
<body>
    <div>
        <input type="text" id="input">
        <span id="text"></span>
    </div>
</body>
</html>
<script>
    var obj = {};
    var obj1 = new Proxy(obj, {
        // target就是第一个参数obj, receive就是返回的obj(返回的proxy对象)
        get: function (target, key, receive) {
            // 返回该属性值
            return target[key];
        },
        set: function (target, key, newVal, receive) {
            // 执行赋值操作
            target[key] = newVal;
            document.getElementById('text').innerHTML = target[key];
        }
    })
    document.addEventListener('keyup', function (e) {
        obj1[0] = e.target.value;
    });
</script>

3.proxy相较于object.defineProperty的优势
*直接监听对象而非属性
*直接监听数组的变化
*拦截方式较多(有13种方式)
*Proxy返回一个新对象,可以只操作新对象达到目的,而Object.defineProperty只能遍历对象属性直接修改(需要用深拷贝进行修改)
*Proxy作为新标准将受到浏览器厂商重点持续的性能优化

posted @ 2022-03-22 12:19  自在一方  阅读(78)  评论(0编辑  收藏  举报