之前也用了一段時(shí)間Vue暇屋,對(duì)其用法也較為熟練了青自,但是對(duì)各種用法和各種api使用都是只知其然而不知其所以然统屈。最近利用空閑時(shí)間嘗試的去看看Vue的源碼,以便更了解其具體原理實(shí)現(xiàn)撑毛,跟著學(xué)習(xí)學(xué)習(xí)书聚。
Proxy 對(duì) data 代理
傳的 data 進(jìn)去的為什么可以用this.xxx訪問(wèn),而不需要 this.data.xxx 呢?
// vue\src\core\instance\state.js
const sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
}
export function proxy (target: Object, sourceKey: string, key: string) {
sharedPropertyDefinition.get = function proxyGetter () {
return this[sourceKey][key]
}
sharedPropertyDefinition.set = function proxySetter (val) {
this[sourceKey][key] = val
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}
function initData (vm: Component) {
let data = vm.$options.data
//...
const keys = Object.keys(data)
//...
let i = keys.length
while (i--) {
const key = keys[i]
//....
proxy(vm, `_data`, key)
}
observe(data, true /* asRootData */)
}
這段代碼看起來(lái)還是很簡(jiǎn)單的藻雌,將 data 中得 key 遍歷一遍雌续,然后全部新增到實(shí)例上去,當(dāng)我們?cè)L問(wèn)修改 this.xxx 得時(shí)候胯杭,都是在訪問(wèn)修改 this._data.xxx
observer 模塊
模塊源碼路徑 vue\src\core\observer
observer 模塊可以說(shuō)是 Vue 響應(yīng)式得核心了驯杜,observer 模塊主要是 Observer、Dep做个、Watcher這三個(gè)部分了
- Observer 觀察者鸽心,對(duì)數(shù)據(jù)進(jìn)行觀察和依賴收集等
- Dep 是 Observer 和 Watcher 得一個(gè)橋梁,Observer 對(duì)數(shù)據(jù)進(jìn)行響應(yīng)式處理時(shí)候居暖,會(huì)給每個(gè)屬性生成一個(gè) Dep 對(duì)象顽频,然后通過(guò)調(diào)用 dep.depend() ,如果當(dāng)前存在 Watcher 將當(dāng)前 Dep 加入到 Watcher 中,然后在將 Watcher 添加到當(dāng)前 Dep 中
- Watcher 訂閱者膝但,數(shù)據(jù)變化會(huì)收到通知冲九,然后進(jìn)行相關(guān)操作,例如視圖更新等
關(guān)系如下
-------get 收集依賴-------- ----------- 訂閱 -------------
| | | |
| V | |
------------ ------------ -------------
| Obserser | ---- set ---->| Dep |------- 通知 ---->| Watcher |
------------ ------------ -------------
|
update
|
-------------
| View |
-------------
1.Observer
initData() 方法調(diào)用了 observe(data, true /* asRootData */) 先來(lái)看下這個(gè)方法
//對(duì)value 進(jìn)行觀察處理
export function observe (value: any, asRootData: ?boolean): Observer | void {
//判斷處理 value 必須是對(duì)象 并且不能是 VNode
if (!isObject(value) || value instanceof VNode) {
return
}
let ob: Observer | void
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__
} else if (
shouldObserve &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value)
}
if (asRootData && ob) {
ob.vmCount++
}
return ob
}
如果 data.__ob__ 已經(jīng)存在直接返回跟束,否則new一個(gè)新的 Observer 實(shí)例莺奸,下面是 Observer 類代碼
export class Observer {
value: any;
dep: Dep;
vmCount: number; // number of vms that have this object as root $data
constructor (value: any) {
this.value = value
// 這個(gè)dep 在 value 的屬性新增 刪除時(shí)候會(huì)用到
//value 如果是數(shù)組 也是通過(guò) 這里的進(jìn)行 依賴收集更新的
this.dep = new Dep()
this.vmCount = 0
def(value, '__ob__', this)
if (Array.isArray(value)) {
//這里是對(duì)數(shù)組原型對(duì)象 攔截 處理
if (hasProto) {
protoAugment(value, arrayMethods)
} else {
copyAugment(value, arrayMethods, arrayKeys)
}
this.observeArray(value)
} else {
this.walk(value)
}
}
walk (obj: Object) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i])
}
}
observeArray (items: Array<any>) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
}
在構(gòu)造函數(shù)中,會(huì)給 value(data)增加 __ob__ (當(dāng)前 Observer實(shí)例 ) 屬性冀宴。如果 value 是數(shù)組灭贷,會(huì)調(diào)用 observeArray 對(duì)數(shù)組進(jìn)行遍歷,在調(diào)用 observe 方法對(duì)每個(gè)元素進(jìn)行觀察略贮。如果是對(duì)象甚疟,調(diào)用 walk 遍歷 value 去調(diào)用 defineReactive 去修改屬性的 get/set仗岖。
//defineReactive 函數(shù)
export function defineReactive (
obj: Object,
key: string, //遍歷的key
val: any,
customSetter?: ?Function,
shallow?: boolean
) {
const dep = new Dep()
const property = Object.getOwnPropertyDescriptor(obj, key)
if (property && property.configurable === false) return
// cater for pre-defined getter/setters
const getter = property && property.get
const setter = property && property.set
if ((!getter || setter) && arguments.length === 2) {
val = obj[key]
}
//如果 key 的值是 對(duì)象 的話,對(duì)其 value 也會(huì)進(jìn)行響應(yīng)處理
let childOb = !shallow && observe(val)
//為當(dāng)前 key 添加get/set
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
dep.depend() //對(duì)當(dāng)前屬性 進(jìn)行依賴收集
if (childOb) {
//如果屬性值是 對(duì)象 览妖,則對(duì)屬性值本身進(jìn)行依賴收集
childOb.dep.depend()
if (Array.isArray(value)) {
//如果值是數(shù)組 對(duì)數(shù)組的每個(gè)元素進(jìn)行依賴收集
dependArray(value)
}
}
}
return value
},
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
if (getter && !setter) return
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
//對(duì)新值 進(jìn)行觀察處理
childOb = !shallow && observe(newVal)
//通知 Watcher
dep.notify()
}
})
}
function dependArray (value: Array<any>) {
for (let e, i = 0, l = value.length; i < l; i++) {
e = value[i]
e && e.__ob__ && e.__ob__.dep.depend()
if (Array.isArray(e)) {
dependArray(e)
}
}
}
上面有兩個(gè)地方有存在 Dep
-
一個(gè)是Observer 類 屬性上有個(gè)Dep,這里主要是對(duì)數(shù)組(數(shù)組沒(méi)有g(shù)et/set不能像對(duì)象屬性那樣)和對(duì)象本身進(jìn)行依賴收集和通知
- 一個(gè)是對(duì)屬性get/set處理時(shí)候的Dep,這個(gè)主要是對(duì)象的屬性進(jìn)行依賴收集和通知
2.Dep
Dep 是 Observer 與 Watcher 橋梁轧拄,也可以認(rèn)為Dep是服務(wù)于Observer的訂閱系統(tǒng)。Watcher訂閱某個(gè)Observer的Dep讽膏,當(dāng)Observer觀察的數(shù)據(jù)發(fā)生變化時(shí)檩电,通過(guò)Dep通知各個(gè)已經(jīng)訂閱的Watcher。
export default class Dep {
static target: ?Watcher;
id: number;
subs: Array<Watcher>;
constructor () {
this.id = uid++
this.subs = [] //Watcher實(shí)例
}
//接收的參數(shù)為Watcher實(shí)例府树,并把Watcher實(shí)例存入記錄依賴的數(shù)組中
addSub (sub: Watcher) {
this.subs.push(sub)
}
//與addSub對(duì)應(yīng)俐末,作用是將Watcher實(shí)例從記錄依賴的數(shù)組中移除
removeSub (sub: Watcher) {
remove(this.subs, sub)
}
//依賴收集
depend () {
if (Dep.target) { //存放當(dāng)前Wather實(shí)例
//將當(dāng)前 Dep 存放到 Watcher(觀察者) 中的依賴中
Dep.target.addDep(this)
}
}
//通知依賴數(shù)組中所有的watcher進(jìn)行更新操作
notify () {
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
Dep.target = null
const targetStack = []
export function pushTarget (target: ?Watcher) {
targetStack.push(target)
Dep.target = target
}
export function popTarget () {
targetStack.pop()
Dep.target = targetStack[targetStack.length - 1]
}
3.Watcher
先看 Watcher 的構(gòu)造函數(shù)
constructor(
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean)
{
...
if (typeof expOrFn === 'function') {
this.getter = expOrFn
} else {
this.getter = parsePath(expOrFn)
if (!this.getter) {
this.getter = noop
}
}
this.value = this.lazy
? undefined
: this.get()
}
expOrFn,對(duì)于初始化用來(lái)渲染視圖的 watcher 來(lái)說(shuō)奄侠,就是render方法卓箫,對(duì)于computed來(lái)說(shuō)就是表達(dá)式,對(duì)于watch才是key垄潮,而getter方法是用來(lái)取value的烹卒。最后調(diào)用了get()方法
get () {
//將Dep.target設(shè)置為當(dāng)前watcher實(shí)例
pushTarget(this)
let value
const vm = this.vm
try {
// 執(zhí)行一次get 收集依賴
value = this.getter.call(vm, vm)
} catch (e) {
if (this.user) {
handleError(e, vm, `getter for watcher "${this.expression}"`)
} else {
throw e
}
} finally {
if (this.deep) {
traverse(value)
}
popTarget()
this.cleanupDeps() //清楚依賴
}
return value
}
假如當(dāng)前Watcher實(shí)例中 getter 是 render,當(dāng)render遇到模板中的{{xxx}}表達(dá)式的時(shí)候魂挂,就是去讀取 data.xxx甫题,這個(gè)時(shí)候就觸發(fā) data.xxx 的 get方法,這個(gè)時(shí)候 get 中會(huì)執(zhí)行Dep.depend(),而此時(shí) Dep.target 就是當(dāng)前 watcher 涂召,然后調(diào)用 watcher.addDep()坠非。也就將data.xxx 與 當(dāng)前watcher 關(guān)聯(lián)起來(lái)了
//watcher 的其他方法
//接收參數(shù)dep(Dep實(shí)例),讓當(dāng)前watcher訂閱dep
addDep (dep: Dep) {
const id = dep.id
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id)
this.newDeps.push(dep)
if (!this.depIds.has(id)) {
//將watcher實(shí)例 也添加到 Dep實(shí)例中
dep.addSub(this)
}
}
}
//清楚對(duì)dep的訂閱信息
cleanupDeps () {
}
//立刻運(yùn)行watcher或者將watcher加入隊(duì)列中
update () {
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
}
//運(yùn)行watcher果正,調(diào)用this.get()求值炎码,然后觸發(fā)回調(diào)
run () {
if (this.active) {
const value = this.get()
if (
value !== this.value || isObject(value) || this.deep
) {
const oldValue = this.value
this.value = value
if (this.user) {
try {
this.cb.call(this.vm, value, oldValue)
} catch (e) {
handleError(e, this.vm, `callback for watcher "${this.expression}"`)
}
} else {
this.cb.call(this.vm, value, oldValue)
}
}
}
}
//調(diào)用this.get()求值
evaluate () {
this.value = this.get()
this.dirty = false
}
//遍歷this.deps,讓當(dāng)前watcher實(shí)例訂閱所有dep
depend () {
let i = this.deps.length
while (i--) {
this.deps[i].depend()
}
}
//去除當(dāng)前watcher實(shí)例所有的訂閱
teardown () {
if (this.active) {
if (!this.vm._isBeingDestroyed) {
remove(this.vm._watchers, this)
}
let i = this.deps.length
while (i--) {
this.deps[i].removeSub(this)
}
this.active = false
}
}