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>隐藏滚动条</title>
</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="main"></div>
<script>
let main = document.querySelector('.main')
let obj = {
text: '文本'
}
const handler = {
get: function (value, prop) {
console.log('get被触发了')
main.innerHTML = value.text
},
set: function (obj, prop, value) {
obj[prop] = value;
main.innerHTML = value
return true;
}
}
let textProxy = new Proxy(obj, handler)
textProxy.text
setTimeout(() => {
textProxy.text = '视频'
}, 5000)
</script>
</body>
</html>