由於對Vue.js很感興趣,並且平時工做的技術棧也是Vue.js,這幾個月花了些時間研究學習了一下Vue.js源碼,並作了總結與輸出。 文章的原地址:https://github.com/answershuto/learnVue。 在學習過程當中,爲Vue加上了中文的註釋https://github.com/answershuto/learnVue/tree/master/vue-src,但願能夠對其餘想學習Vue源碼的小夥伴有所幫助。 可能會有理解存在誤差的地方,歡迎提issue指出,共同窗習,共同進步。javascript
依賴收集是在響應式基礎上進行的,不熟悉的同窗能夠先了解《響應式原理》。vue
先看下面這段代碼java
new Vue({ template: `<div> <span>text1:</span> {{text1}} <span>text2:</span> {{text2}} <div>`, data: { text1: 'text1', text2: 'text2', text3: 'text3' } });
按照以前《響應式原理》中的方法進行綁定則會出現一個問題——text3在實際模板中並無被用到,然而當text3的數據被修改的時候(this.text3 = 'test')的時候,一樣會觸發text3的setter致使從新執行渲染,這顯然不正確。git
當對data上的對象進行修改值的時候會觸發它的setter,那麼取值的時候天然就會觸發getter事件,因此咱們只要在最開始進行一次render,那麼全部被渲染所依賴的data中的數據就會被getter收集到Dep的subs中去。在對data中的數據進行修改的時候setter只會觸發Dep的subs的函數。github
定義一個依賴收集類Dep。閉包
class Dep () { constructor () { this.subs = []; } addSub (sub: Watcher) { this.subs.push(sub) } removeSub (sub: Watcher) { remove(this.subs, sub) } notify () { // stabilize the subscriber list first const subs = this.subs.slice() for (let i = 0, l = subs.length; i < l; i++) { subs[i].update() } } }
訂閱者,當依賴收集的時候回addSub到sub中,在修改data中數據的時候會觸發Watcher的notify,從而回調渲染函數。函數
class Watcher () { constructor (vm, expOrFn, cb, options) { this.cb = cb; this.vm = vm; /*在這裏將觀察者自己賦值給全局的target,只有被target標記過的纔會進行依賴收集*/ Dep.target = this; /*觸發渲染操做進行依賴收集*/ this.cb.call(this.vm); } update () { this.cb.call(this.vm); } }
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方法進行渲染。學習
做者:染陌this
Email:answershuto@gmail.com or answershuto@126.comspa
Github: https://github.com/answershuto
Blog:http://answershuto.github.io/
知乎專欄:https://zhuanlan.zhihu.com/ranmo
掘金: https://juejin.im/user/58f87ae844d9040069ca7507
osChina:https://my.oschina.net/u/3161824/blog
轉載請註明出處,謝謝。
歡迎關注個人公衆號