Vue2/Vue3 响应式原理

Vue 2.x 版本与 Vue 3.x 版本的响应式实现有所不同
Vue 2.x 响应式基于 ES5 的 Object.defineProperty 实现
Vue 3.x 响应式基于 ES6 的 Proxy 实现

Vue 2 响应式原理

  • Vue 2.x 响应式基于 ES5 的 Object.defineProperty 实现
    • 设置 data 后,遍历所有属性,转换为 Getter、Setter,从而在数据变化时进行试图更新等操作

基础效果

var obj = {
    name: 'GD',
    age: 18
}
var num = 'nan'
Object.defineProperty(obj, 'sex', {
    get () {
        console.log(1)
        return num
    },
    set (nVal) {
        console.log(2)
        num = nVal
    }
})

改进

  • 上述版本只是雏形,问题如下:
    • 操作中只坚挺了一个属性,多个属性无法处理
    • 无法监听数组变化(Vue 中同样存在
    • 无法处理属性也为对象的情况
  • 改进
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">初始内容</div>
    <script>
        let data = {
            msg: 'hello',
            age: 18,
            arr: [1, 2, 3, 4, 5],
            obj: {
                name: 'hh',
                age: 1888
            }
        };

        let vm = {};

        // 封装为函数用于对数据进行响应式处理
        const createReactive = (function () {
            const arrMethodName = ['push', 'pop']
            const customProto = {}
            customProto.__proto__ = Array.prototype
            arrMethodName.forEach(method => {
                customProto[method] = function () {
                    const result = Array.prototype[method].apply(this, arguments)
                    document.querySelector('#app').textContent = this
                    return result
                }
            })

            // 需要进行数据劫持的主体功能,也是递归时需要的功能
            return function (data, vm) {
                Object.keys(data).forEach(key => {
                    if (Array.isArray(data[key])) {
                        data[key].__proto__ = customProto
                    } else if (typeof data[key] === 'object' && data[key] !== null) {
                        vm[key] = {}
                        createReactive(data[key], vm[key])
                        return
                    }
                    Object.defineProperty(vm, key, {
                        enumerable: true,
                        configurable: true,
                        get() {
                            console.log('访问成功')
                            return data[key]
                        },
                        set(newValue) {
                            data[key] = newValue
                            document.querySelector('#app').innerHTML = data[key]
                        }
                    })
                })
            }
        })()
    
        createReactive(data, vm)

    </script>
</body>

</html>

Vue 3 响应式原理

Vue 3.x 与 Vue 2.x 的区别为数据响应式是通过 Proxy 实现的,其他相同

porxy 回顾

const data = {
    msg: 'hello',
    arr: [1, 2, 3],
    obj: {
        name : 'GD',
        age: 18
    }
}
const newP = new Proxy(data, {
    get (target, property, receiver) {
        console.log(target)
        console.log(property)
        console.log(receiver)
        return target[property]
    },
    set (target, property, value, receiver) {
        console.log(target)
        console.log(property)
        console.log(value)
        console.log(receiver)
        return target[property] = value
    }
})

proxy 实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">初始内容</div>
    <script>
        const data = {
            msg: 'hello',
            arr: [1, 2, 3],
            obj: {
                name: 'GD'
            }
        }
        const vm = new Proxy(data, {
            get (target, key) {
                return target[key]
            },
            set (target, key, newValue) {
                target[key] = newValue
                document.querySelector('#app').innerHTML = target[key]
            }
        })
    </script>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值