大家好,又见面了,我是你们的朋友全栈君。
<div id="app">
{
{message}}
</div>
<script src='./js/vue.js'></script>
<script> const app = new Vue({
el: '#app', data: {
message: '哈哈哈哈', name: 'coderYYY' } }) </script>
object.defineProperty
-> 监听对象属性的改变Proxy
const obj = {
message: '哈哈哈哈',
name: 'yyy'
}
// 1.监听值的改变 -> Object.defineProperty(属性所在的对象,要添加或者修改的对象属性,属性描述符)
Object.keys(obj).forEach(key => {
let value = obj[key]
Object.defineProperty(obj, key, {
set(newValue) {
console.log('监听' + key + '改变');
// 告诉谁?谁用告诉谁?谁在用?
// 根据解析html代码,获取到哪些人有用属性
// 张三/李四/王五 在用
value = newValue
// dep.notify()// 通知
},
get() {
// 谁用一次就会调用一次get
// 张三: get -> update
// 李四: get -> update
// 王五: get -> update
console.log('获取' + key + '对应的值');
return value
}
})
})
// 2.发布者订阅者模式
// 发布者
class Dep {
// 存储所有对属性有依赖的东西
constructor() {
this.subscribe = [] // subscribe 订阅 这个数组记录谁要订阅属性
}
addSub(watcher) {
this.subscribe.push(watcher)
}
notify(){
this.subscribe.forEach(item=>{
item.update()
})
}
}
const dep = new Dep()
// 订阅者
class Watcher {
constructor(name) {
this.name = name;
}
update() {
console.log(this.name + '发生update');
}
}
const w1 = new Watcher('张三')
dep.addSub(w1)
const w2 = new Watcher('李四')
dep.addSub(w2)
const w3 = new Watcher('王五')
dep.addSub(w3)
dep.notify()
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/135185.html原文链接:https://javaforall.cn