寫在前面
因為對Vue.js很感興趣,而且平時工作的技術棧也是Vue.js,這幾個月花了些時間研究學習了一下Vue.js源碼,並做了總結與輸出。
文章的原地址:https://github.com/answershuto/learnVue。
在學習過程中,為Vue加上了中文的注釋https://github.com/answershuto/learnVue/tree/master/vue-src,希望可以對其他想學習Vue源碼的小伙伴有所幫助。
可能會有理解存在偏差的地方,歡迎提issue指出,共同學習,共同進步。
依賴收集是在響應式基礎上進行的,不熟悉的同學可以先了解《響應式原理》。
為什么要依賴收集
先看下面這段代碼
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導致重新執行渲染,這顯然不正確。
先說說Dep
當對data上的對象進行修改值的時候會觸發它的setter,那么取值的時候自然就會觸發getter事件,所以我們只要在最開始進行一次render,那么所有被渲染所依賴的data中的數據就會被getter收集到Dep的subs中去。在對data中的數據進行修改的時候setter只會觸發Dep的subs的函數。
定義一個依賴收集類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()
}
}
}
Watcher
訂閱者,當依賴收集的時候回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方法進行渲染。
關於
作者:染陌
Email:answershuto@gmail.com or answershuto@126.com
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
轉載請注明出處,謝謝。
歡迎關注我的公眾號