proxy实现数据响应式

<p id="paragraph"></p>
	<input type="text" id="input">

	<script>
		const paragraph = document.getElementById('paragraph');
		const input = document.getElementById('input');
		// 需要代理的数据对象
		const data = {
			text:'hello world'
		};
		const handler = {
			// 监控data中text属性的变化
			set:function(target, prop, value){
				if (prop === 'text') {
					// 更新值
					target[prop] = value;
					// 更新视图
					paragraph.innerHTML = value;
					input.value = value;
					return true;
				}else{
					return false;
				}
			}
		}
		// 构造proxy对象
		const myText = new Proxy(data, handler);
		// 添加input监听事件
		input.addEventListener('input', function(e){
			myText.text = e.target.value
		},false);
		// 初始化值
		myText.text = data.text;

通过proxy创建了myText实例,通过拦截myText中text属性set方法来更新视图变化,实现了一个简单的数据绑定。

猜你喜欢

转载自blog.csdn.net/weixin_44372019/article/details/89533309
今日推荐