Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

理解vue响应式原理(3)--watch #15

Open
conan1992 opened this issue Jun 13, 2020 · 0 comments
Open

理解vue响应式原理(3)--watch #15

conan1992 opened this issue Jun 13, 2020 · 0 comments

Comments

@conan1992
Copy link
Owner

conan1992 commented Jun 13, 2020

watch

原理:传入的第一个参数是个函数,里面去读取响应式的属性,从而将依赖添加到这个属性的dep里;当属性值发生改变,能够被监测到,从而执行回调函数;

watch(
  () => data.msg,
  (newVal, oldVal) => {
    console.log('newVal: ', newVal)
    console.log('old: ', oldVal)
  }
)

实现:

//watch.js
import Watcher from "./watcher"

export default function watch(getter, callback) {
    new Watcher(getter, {
        watch: true,
        callback: callback
    })
}
//watcher.js
import Dep, {pushTarget, popTarget } from "./dep"

export default class Watcher {
    constructor( getter, options = {} ){
        let {computed, watch, callback} = options;
        this.getter = getter;
        this.computed = computed;
        this.watch = watch;
        this.callback = callback;
        this.value = undefined;
        if(computed){
            this.dep = new Dep();
        }else{
            this.get();
        }
        
    }
    depend(){
        this.dep.depend()
    }
    get(){
        pushTarget(this);
        this.value = this.getter();
        popTarget();
        return this.value
    }
    update(){
        if(this.computed){
            this.get();
            this.dep.notify();
        }else if(this.watch){
            let oldVal = this.value;
            this.get();
            this.callback && this.callback(this.value, oldVal)
        }else{
            this.get();
        }
        
    }
}

源码
参考:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant