We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
原理:传入的第一个参数是个函数,里面去读取响应式的属性,从而将依赖添加到这个属性的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(); } } }
源码 参考:
The text was updated successfully, but these errors were encountered:
No branches or pull requests
watch
原理:传入的第一个参数是个函数,里面去读取响应式的属性,从而将依赖添加到这个属性的dep里;当属性值发生改变,能够被监测到,从而执行回调函数;
实现:
源码
参考:
The text was updated successfully, but these errors were encountered: