当前第2页 返回上一页
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Dep{
constructor(){
this.subs = [];
}
addSub(sub:Watcher){
this.subs.push(sub)
}
removeSub(sub:Watcher){
remove(this.subs,sub)
}
notify(){
const subs = this.subs.slice()
for (let i = 0;l=subs.length;i<1;i++){
subs[i].update()
}
}
}
function remove(arr,item){
if (arr.length){
const index = arr.indexOf(item)
if (index>-1){
return arr.splice(index,1)
}
}
}
|
Watcher
订阅者,当依赖收集的时候会addSub到sub中,在修改data中数据的时候会触发dep对象的notify,通知所有Watcher对象去修改对应视图。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Watcher {
constructor (vm, expOrFn, cb, options) {
this.cb = cb;
this.vm = vm;
Dep.target = this;
this.cb.call(this.vm);
}
update () {
this.cb.call(this.vm);
}
}
|
开始依赖收集
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class Vue {
constructor(options) {
this._data = options.data;
observer(this._data, options.render);
let watcher = new Watcher(this, );
}
}
function defineReactive (obj, key, val, cb) {
const dep = new Dep();
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: ()=>{
if (Dep.target) {
dep.addSub(Dep.target);
}
},
set:newVal=> {
dep.notify();
}
})
}
Dep.target = null;
|
将观察者Watcher实例赋值给全局的Dep.target,然后触发render操作只有被Dep.target标记过的才会进行依赖收集。有Dep.target的对象会将Watcher的实例push到subs中,在对象被修改触发setter操作的时候dep会调用subs中的Watcher实例的update方法进行渲染。
本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的JavaScript视频教程栏目!以上就是vue响应式原理及依赖收集的介绍 (附代码)的详细内容,更多文章请关注木庄网络博客!
返回前面的内容
相关阅读 >>
详解javascript数组开头添加元素的3种方法
node批量下载文件到本地的方法介绍(附代码)
html和js实现简单的计算器
javascript怎么设置css
javascript是干啥的
javascript在nodejs环境下执行机制和事件循环
javascript函数必须有返回值吗
javascript怎么将array转为字符串
javascript怎么修改html内容
聊聊javascript中eval()函数的用法
更多相关阅读请进入《javascript》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » vue响应式原理及依赖收集的介绍 (附代码)