vue响应式原理及依赖收集的介绍 (附代码)


当前第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;

 

        /*在这里将观察者本身赋值给全局的target,只有被target标记过的才会进行依赖收集*/

        Dep.target = this;

        /*Github:https://github.com/answershuto*/

        /*触发渲染操作进行依赖收集*/

        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) {

    /*在闭包内存储一个Dep对象*/

    const dep = new Dep();

 

    Object.defineProperty(obj, key, {

        enumerable: true,

        configurable: true,

        get: ()=>{

            if (Dep.target) {

                /*Watcher对象存在全局的Dep.target中*/

                dep.addSub(Dep.target);

            }

        },

        set:newVal=> {

            /*只有之前addSub中的函数才会触发*/

            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》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...