实现Vue-MVVM-step1

133 阅读1分钟


<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Vue-MVVM</title>
	</head>
	<body>
		<input type="text" id="input1" value="" oninput="myFun()" />
		<input type="text" id="input2" />
	</body>
	<script>
		function myFun() {
			o._data.test = document.getElementById('input1').value
		}
		/* 这个函数用来模拟视图更新 */
		function cb(val) {
			console.log('试图更新啦~~');
			document.getElementById('input2').value = val
		}
		/* 遍历所有属性的方式对该对象的每一个属性都通过 defineReactive  */
		function observer(value) {
			if (!value || (typeof value !== 'object')) {
				return;
			}
			Object.keys(value).forEach((key) => {
				defineReactive(value, key, value[key]);
			})
		}
		/* 实现对对象的「响应式」 */
		function defineReactive(obj, key, val) {
			Object.defineProperty(obj, key, {
				enumerable: true,		// 能否被遍历,比如 for in,默认值为 false
				configurable: true,		// 描述该属性的描述符能否被改变,默认值为 false
				get: function reactiveGetter() {		// 取值的时候调用,默认值为 false
					return val;
				},
				set: function reactiveSetter(newVal) {		// 设置值的时候使用
					if (newVal === val) return;
					cb(newVal);
				}
			});
		}
		/* 声明类 */
		class Vue {
			constructor(options) {
				this._data = options.data;
				observer(this._data)
			}
		}
		/* 创建实例 */
		var o = new Vue({
			data: {
				test: ""
			}
		})
	</script>
</html>