带薪摸鱼:手写一下vue2和vue3的响应式核心原理
vue2:
<body>
<div>
<input type="text" id="input">
<span id="text"></span>
</div>
<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>
</body>
vue3:
<body>
<div>
<input type="text" id="input">
<span id="text"></span>
</div>
</body>
<script>
var obj = {};
var obj1 = new Proxy(obj, {
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>