vue响应式原理
1.Vue内部如何监听数据的改变
通过Object.defineProperty监听对象属性的改变
2.当数据发生改变时,Vue如何通知界面进行刷新
通过发布订阅模式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<script src="../node_modules/vue/dist/vue.js"></script>
<script>
let obj = {
message: 123,
name: 456
}
const dep = new Dep()
Object.keys(obj).forEach(key => {
let value = obj[key]
Object.defineProperty(obj, key, {
set(newVal) {
// 监听key值的改变
// 一个属性对应一个Dep对象,因为这样的话,当该属性的值改变时,对应数据才能够改变
dep.notify()
value = newVal
},
get() {
// 解析html代码,提取格式
// 之后根据格式创建订阅,当set时触发notify方法
// const w1 = new Watcher('a') --'a'只是模拟
// dep.addSub(watcher)
return value
}
})
})
// 发布订阅模式
// 发布者
class Dep {
constructor() {
this.subs = []
}
addSub(watcher) {
this.subs.push(watcher)
}
notify() {
this.subs.forEach(watcher => {
watcher.update()
})
}
}
// 订阅者
class Watcher {
constructor(name) {
this.name = name
}
update() {
console.log(this.name + '发生update')
}
}
const vm = new Vue({
el: '#app',
data: {
message: 123,
name: 456
}
})
</script>
</body>
</html>


浙公网安备 33010602011771号