簡介
響應式系統是vue框架核心的部分,數據對象僅僅是普通的 js對象。當我們改變數據時,視圖也會被改變,本文就來探究一下vue 的響應式原理。
Object.defineProperty
vue響應式的核心是使用了es5 新增的API Object.defineProperty(因此vue不支持ie8) 。Object.defineProperty的作用就是直接在一個對象上定義一個新屬性,或者修改一個已經存在的屬性, 它允許我們爲對象的實行設置get和set方法,在對象取值和賦值會調用這兩個方法,所以我們可以在賦值和取值時劫持這兩個方法,觸發更新試視圖的操作。
const obj = {
attr: '測試',
}
let val = '劫持'
Object.defineProperty(obj, 'attr', {
enumberable: true,
configurable: true,
get() {
return val
},
set(newVal) {
val = newVal
console.log('更新視圖的操作')
}
})
console.log(obj.attr)
obj.attr = '賦值'
console.log(obj.attr)
發佈訂閱模式
vue的依賴收集使用了發佈訂閱模式。
class Dep {
constructor() {
// 存放訂閱者的數組
this.subs = []
}
// 增加訂閱者
addSub(sub) {
this.subs.push(sub)
}
// 通知訂閱者
notify() {
this.subs.forEach((sub) => {
sub.update()
})
}
}
const dep = new Dep()
const sub_fn1 = {
update() {
console.log('fn1 update')
}
}
const sub_fn2 = {
update() {
console.log('fn2 update');
}
}
dep.addSub(sub_fn1)
dep.addSub(sub_fn2)
dep.notify()
init
vue在初始化時會條用一系列方法,其中initState對數據data進行了初始化
export function initState (vm: Component) {
vm._watchers = []
const opts = vm.$options
if (opts.props) initProps(vm, opts.props)
if (opts.methods) initMethods(vm, opts.methods)
if (opts.data) {
initData(vm)
} else {
observe(vm._data = {}, true /* asRootData */)
}
if (opts.computed) initComputed(vm, opts.computed)
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
這段代碼對props methods data進行了初始化,我們選擇initData作爲切入點來探究vue的響應式系統。
function initData (vm: Component) {
let data = vm.$options.data
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
if (!isPlainObject(data)) {
data = {}
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
)
}
const keys = Object.keys(data)
const props = vm.$options.props
const methods = vm.$options.methods
let i = keys.length
while (i--) {
const key = keys[i]
if (process.env.NODE_ENV !== 'production') {
// 期待純對象
if (methods && hasOwn(methods, key)) {
warn(
`Method "${key}" has already been defined as a data property.`,
vm
)
}
}
if (props && hasOwn(props, key)) {
process.env.NODE_ENV !== 'production' && warn(
`The data property "${key}" is already declared as a prop. ` +
`Use prop default value instead.`,
vm
)
} else if (!isReserved(key)) {
// 添加代理對象的屬性
proxy(vm, `_data`, key)
}
}
observe(data, true /* asRootData */)
}
這段代碼獲取了data,先判斷了data的類型是不是純對象,然後判斷了data的屬性與props和methods是否衝突,接着在vue 實例對象上添加了訪問數據代理對象_data的同名屬性,最後調用了observe 函數開啓了數據響應式系統。
observe
因爲observe代碼相對比較複雜,有很多邊界條件的判斷,如避免收集重複的依賴,如何深度觀測,如何處理數組與對象等,爲了簡化理解,我們只關注最核心的邏輯。
export function observe (value: any, asRootData: ?boolean): Observer | void {
// data是對象且是Vnode實例時,繼續
if (!isObject(value) || value instanceof VNode) {
return
}
let ob: Observer | void
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__ // ob保存 Observer 實例,避免重複觀測
} 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
}
這段代碼是observe的全部內容,observe對data進行了一個判斷, 如果不是對象或者不是Vnode的實例,不進行監測。然後判斷data是否有__ob__ 屬性,如果有直接賦值,避免重複監測,因爲對象被監測後會添加__ob__ 屬性。 緊接着又有一些是否可以監測的條件判斷,當滿足時,就會創建一個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
this.dep = new Dep()
this.vmCount = 0
def(value, '__ob__', this)
if (Array.isArray(value)) {
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])
}
}
}
上面是Observer類。this.value = value 是實例化對象時傳進來數據的引用,可以看到def(value, ‘ob’, this)這句代碼爲監測對象添加了__ob__屬性,然後判斷時純對象還是數組,分別走不同的監測邏輯。因爲對象相對簡單,我們選擇對象理一下邏輯。當數據是純對象時,會調用walk函數,遍歷data所有可枚舉的屬性,然後循環將這些屬性作爲參數調用defineReactive 函數。
export function defineReactive (
obj: Object,
key: string,
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]
}
let childOb = !shallow && observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
dep.depend()
if (childOb) {
childOb.dep.depend()
if (Array.isArray(value)) {
dependArray(value)
}
}
}
return value
},
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter()
}
// #7981: for accessor properties without setter
if (getter && !setter) return
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
dep.notify()
}
})
}
這段代碼相對比較複雜,有許多邊界條件的判斷,我們不必關心實現實踐的細節,只關注Object.defineProperty即可。defineReactive 的核心是將數據對象的屬性用Object.defineProperty進行數據劫持 const dep = new Dep()定義了依賴收集器。Object.defineProperty定義了get和set方法,當執行賦值時,會調用get函數執行dep.depend()進行依賴收集,當值改變時調用set觸發dep.notify(),進行視圖更新。
總結
vue響應式系統的核心原理是數據劫持結合發佈訂閱模式,在vue初始化過程中,vue會對templae編譯生成指令對象與訂閱者關聯,通過Object.defineProperty爲數據對象添加getter和setter,並執行gettter,添加訂閱者。當數據改變時,觸發setter,訂閱者執行指令更新,指令是對原生dom對象的封裝,從而導致視圖的更新。