Vue响应式的理解和简单的实现

以下是本人对vue响应式的个人理解:

vue响应式依赖的两种核心技术:
1.Vue中修改数据,Vue内部是如何监听message数据的变化的

  • Object.defineProperty() -> 监听对象属性的改变

2.当数据发生改变,Vue是如何知道要通知哪些数据,界面发生刷新

  • 发布订阅模式

前两篇博客分别对 Object.defineProperty()发布订阅模式实现 做了单独的说明,现在结合两种技术,简单实现vue的响应式

点击按钮 ,修改person对象中的age属性,修改后通知每一位订阅者,让其响应消息

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<button id="btn">按钮</button>
	</body>
	<script type="text/javascript">
	    //发布者类
		class sub {
			constructor() {
				this.pond = []
			}
			add(obj) {
				let flag = this.pond.some(item => {
					return item === obj
				})
				 !flag ? this.pond.push(obj) : null   //去重处理
			}
			remove(obj) {
				this.pond = this.pond.filter((item) => {
					return item !== obj
				})
			}
			fire(...args) {
				this.pond.forEach((item) => {
					//						item.call(this, ...args)
					item.update(args)
				})
			}
		}

		//订阅者类
		class Watcher {
			constructor(name) {
				this.name = name
			}
			update(arr) {
				console.log(arr[0] + '发生改变', '新值为:' + arr[1])
			}
		}

		var person = {
			name: "xiaojiayu",
			age: 24,
			gender: "man"
		}
		document.getElementById("btn").onclick = function() {
			person.age = 6666
		}

		Object.keys(person).forEach(key => {
			let value = person[key]
			Object.defineProperty(person, key, {
				set(newValue) {
					console.log('监听到' + key + '的改变,新的值为' + newValue)
					//监听到值的改变,通知每一位订阅者,让他们也修改为新值
					Dep.fire(key, newValue)
					value = newValue
				},
				get() {
					console.log('有人来获取' + key + '对应的值了')
					return value
				}
			})
		})

		const Dep = new sub()
		const w1 = new Watcher('小红')
		Dep.add(w1)
		const w2 = new Watcher('小明')
		Dep.add(w2)
		const w3 = new Watcher('小花')
		Dep.add(w3)
		
	</script>
</html>

成功响应消息:
在这里插入图片描述

如何不足之处,还望指出,相互学习,近期疫情紧张,延迟开学,各位好好待在家,最后,武汉加油

发布了41 篇原创文章 · 获赞 3 · 访问量 4589

猜你喜欢

转载自blog.csdn.net/fesfsefgs/article/details/104191024