小编这次要给大家分享的是Vue如何实现发布订阅模式,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。
vue项目中不同组件间通信一般使用vuex,通常情况下vuex和EventBus不应该混用,不过某些场景下不同组件间只有消息的交互,这时使用EventBus消息通知的方式就更合适一些。
图解
html
<body>
<script src="./Dvue.js"></script>
<script>
const app = new DVue({
data: {
test: "I am test",
foo: {
bar: "bar"
}
}
})
app.$data.test = "hello world!"
// app.$data.foo.bar = "hello!"
</script>
</body>
Dvue.js
class DVue {
constructor(options) {
this.$options = options
// 数据响应化
this.$data = options.data
this.observe(this.$data)
// 模拟一下watcher创建
// 激活get 并将依赖添加到deps数组上
new Watcher()
this.$data.test
new Watcher()
this.$data.foo.bar
}
observe(value) {
// 判断value是否是对象
if (!value || typeof value !== 'object') {
return
}
// 遍历该对象
Object.keys(value).forEach(key => {
this.defineReactive(value, key, value[key])
})
}
// 数据响应化
defineReactive(obj, key, val) {
// 判断val内是否还可以继续调用(是否还有对象)
this.observe(val) // 递归解决数据嵌套
// 初始化dep
const dep = new Dep()
Object.defineProperty(obj, key, {
get() {
// 读取的时候 判断Dep.target是否有,如果有则调用addDep方法将Dep.target添加到deps数组上
Dep.target && dep.addDep(Dep.target)
return val
},
set(newVal) {
if (newVal === val) {
return;
}
val = newVal
// console.log(`${key}属性更新了:${val}`)
dep.notify() // 更新时候调用该方法
}
})
}
}
// Dep: 用来管理Watcher
class Dep {
constructor() {
// 这里存放若干依赖(watcher) |一个watcher对应一个属性
this.deps = [];
}
// 添加依赖
addDep (dep) {
this.deps.push(dep)
}
// 通知方法
notify() {
this.deps.forEach(dep => dep.update())
}
}
// Watcher
class Watcher {
constructor () {
// 将当前watcher实例指定到Dep静态属性target上
Dep.target = this // 当前this就是Watcher对象
}
update() {
console.log('属性更新了')
}
}
看完这篇关于Vue如何实现发布订阅模式的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。