vue2從數(shù)據(jù)變化到視圖變化發(fā)布訂閱模式詳解
引言
發(fā)布訂閱者模式是最常見的模式之一,它是一種一對多的對應關系,當一個對象發(fā)生變化時會通知依賴他的對象,接受到通知的對象會根據(jù)情況執(zhí)行自己的行為。
假設有財經(jīng)報紙送報員financialDep,有報紙閱讀愛好者a,b,c,那么a,b,c想訂報紙就告訴financialDep,financialDep依次記錄a,b,c這三個人的家庭地址,次日,送報員一大早把報紙送到a,b,c家門口的郵箱中,a,b,c收到報紙后都會認認真真的打開閱讀。隨著時間的推移,會有以下幾種場景:
- 有新的訂閱者加入: 有一天d也想訂報紙了,那么找到financialDep,financialDep把d的家庭地址記錄到a,b,c的后面,次日,為a,b,c,d分別送報紙。
- 有訂閱者退出了:有一天a要去旅游了,提前給送報員financialDep打電話取消了訂閱,如果不取消的話,積攢的報紙就會溢出小郵箱。
- 有新的報社開業(yè):有一天鎮(zhèn)子又開了家體育類的報館,送報員是sportDep,b和d也是球類愛好者,于是在sportDep那里做了登記,sportDep的記錄中就有了b和d。
從上面的例子中可以看出,剛開始送報員financialDep的記錄中有a,b和c,先是d加進來后來是a離開,最終financialDep的記錄中有b,c和d。體育類報館開張的時候,b和d也訂閱了報紙,sportDep的記錄中就有了b和d。我們發(fā)現(xiàn),c只訂閱了財經(jīng)類報刊,而b和d既訂閱了財經(jīng)類的報紙也定了財經(jīng)類的報刊。
一、發(fā)布訂閱者模式的特點
從以上例子可以發(fā)現(xiàn)特點:
- 發(fā)布者可以支持訂閱者的加入
- 發(fā)布者可以支持訂閱者的刪除
- 一個發(fā)布者可以有多個訂閱者,一個訂閱者也可以訂閱多個發(fā)布者的消息那可能會有疑問,有沒有可能會有發(fā)布者的刪除,答案是會,但是此時,發(fā)布者已消失,訂閱者再也不會收到消息,也就不會與當前發(fā)布者相關的消息誘發(fā)的行為。好比體育類報館關停了(發(fā)布者刪除)那么b和d在也不會收到體育類報紙(消息),也就不會再閱讀體育類報紙(行為)。
二、vue中的發(fā)布訂閱者模式
以上的例子基本就是vue中發(fā)布訂閱者的大體概況,vue中的發(fā)布者是啥時候定義的?
在new Vue實例化的過程中會執(zhí)行this._init的初始化方法,_init方法中有方法initState:
export function initState (vm: Component) {
// ...
if (opts.data) {
initData(vm)
} else {
observe(vm._data = {}, true /* asRootData */)
}
//...
}
首先看initData對于data的初始化:
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
)
}
// proxy data on instance
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
observe(data, true /* asRootData */)
}
這里首先獲取data,如果data是函數(shù)又會執(zhí)行getData方法。然后,獲取methods和props中的key值,如果已經(jīng)定義過則在開發(fā)環(huán)境進行控制臺警告。其中,proxy的目的是讓訪問this[key]相當于訪問this._data[key]。最后,對數(shù)據(jù)進行響應式處理 observe(data, true /* asRootData */):
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*/
export function observe (value: any, asRootData: ?boolean): Observer | void {
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
}
如果不是對象或者當前值是VNode的實例直接返回。如果當前當前值上有屬性__ob__并且value.__ob__是Observer的實例,那么說明該值已經(jīng)被響應式處理過,直接將value.__ob__賦值給ob并在最后返回即可。如果滿足else if中的條件,則可執(zhí)行ob = new Observer(value):
/**
* Observer class that is attached to each observed
* object. Once attached, the observer converts the target
* object's property keys into getter/setters that
* collect dependencies and dispatch updates.
*/
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 through all properties and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
walk (obj: Object) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i])
}
}
/**
* Observe a list of Array items.
*/
observeArray (items: Array<any>) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
}
Observer是構(gòu)造函數(shù),通過對value是否是數(shù)組的判斷,分別執(zhí)行observeArray和walk,observeArray會對數(shù)組中的元素執(zhí)行observe(items[i]),即通過遞歸的方式對value樹進行深度遍歷,遞歸的最后都會執(zhí)行到walk方法。再看walk中的defineReactive(obj, keys[i])方法:
/**
* Define a reactive property on an Object.
*/
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()
}
})
}
這里就是vue響應式原理、watcher訂閱者收集、數(shù)據(jù)變化時發(fā)布者dep通知subs中訂閱者watcher進行相應操作的主要流程,new Dep()實例化、Object.defineProperty方法、dep.depend()訂閱者收集和dep.notify()是主要的功能。先看發(fā)布者Dep的實例化:
1、dep
import type Watcher from './watcher'
import { remove } from '../util/index'
import config from '../config'
let uid = 0
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
export default class Dep {
static target: ?Watcher;
id: number;
subs: Array<Watcher>;
constructor () {
this.id = uid++
this.subs = []
}
addSub (sub: Watcher) {
this.subs.push(sub)
}
removeSub (sub: Watcher) {
remove(this.subs, sub)
}
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
notify () {
// stabilize the subscriber list first
const subs = this.subs.slice()
if (process.env.NODE_ENV !== 'production' && !config.async) {
// subs aren't sorted in scheduler if not running async
// we need to sort them now to make sure they fire in correct
// order
subs.sort((a, b) => a.id - b.id)
}
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
// The current target watcher being evaluated.
// This is globally unique because only one watcher
// can be evaluated at a time.
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]
}
這里的dep就相當于財經(jīng)或者體育報館,其中定義了屬性id和subs,subs相當于送報員financialDep手中的筆記本,用來是用來記錄訂閱者的數(shù)組。發(fā)布者的消息如何發(fā)給訂閱者,就需要借助Object.defineProperty:
2、Object.defineProperty
對于一個對象的屬性進行訪問或者設置的時候可以為其設置get和set方法,在其中進行相應的操作,這也是vue響應式原理的本質(zhì),也是IE低版本瀏覽器不支持vue框架的原因,因為IE低版本瀏覽器不支持Object.defineProperty方法。
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
// 當訪問屬性的時候,進行訂閱者的收集
},
set: function reactiveSetter (newVal) {
// 當修改屬性的時候,收到發(fā)布者消息的時候進行相應的操作
}
})
在vue中訂閱者有computer watcher計算屬性、watch watcher偵聽器和render watcher渲染watcher。這里先介紹渲染watcher:
3、watcher
let uid = 0
/**
* A watcher parses an expression, collects dependencies,
* and fires callback when the expression value changes.
* This is used for both the $watch() api and directives.
*/
export default class Watcher {
vm: Component;
expression: string;
cb: Function;
id: number;
deep: boolean;
user: boolean;
lazy: boolean;
sync: boolean;
dirty: boolean;
active: boolean;
deps: Array<Dep>;
newDeps: Array<Dep>;
depIds: SimpleSet;
newDepIds: SimpleSet;
before: ?Function;
getter: Function;
value: any;
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
this.vm = vm
if (isRenderWatcher) {
vm._watcher = this
}
vm._watchers.push(this)
// options
if (options) {
this.deep = !!options.deep
this.user = !!options.user
this.lazy = !!options.lazy
this.sync = !!options.sync
this.before = options.before
} else {
this.deep = this.user = this.lazy = this.sync = false
}
this.cb = cb
this.id = ++uid // uid for batching
this.active = true
this.dirty = this.lazy // for lazy watchers
this.deps = []
this.newDeps = []
this.depIds = new Set()
this.newDepIds = new Set()
this.expression = process.env.NODE_ENV !== 'production'
? expOrFn.toString()
: ''
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn
} else {
this.getter = parsePath(expOrFn)
if (!this.getter) {
this.getter = noop
process.env.NODE_ENV !== 'production' && warn(
`Failed watching path: "${expOrFn}" ` +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
)
}
}
this.value = this.lazy
? undefined
: this.get()
}
/**
* Evaluate the getter, and re-collect dependencies.
*/
get () {
pushTarget(this)
let value
const vm = this.vm
try {
value = this.getter.call(vm, vm)
} catch (e) {
if (this.user) {
handleError(e, vm, `getter for watcher "${this.expression}"`)
} else {
throw e
}
} finally {
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value)
}
popTarget()
this.cleanupDeps()
}
return value
}
// watcher還有很多其他自定義方法,用的時候再列舉
}
Watcher實例化的最后會執(zhí)行this.value = this.lazy ? undefined : this.get()方法,默認this.lazy=false,滿足條件執(zhí)行Watcher實例的回調(diào)this.get()方法。 pushTarget(this)定義在dep.js文件中,為全局targetStack中推入當前訂閱者,是一種棧的組織方式。Dep.target = target表示當前訂閱者是正在計算中的訂閱者,全局同一時間點有且只有一個。 然后執(zhí)行value = this.getter.call(vm, vm),這里的this.getter就是
updateComponent = () => {
vm._update(vm._render(), hydrating)
}
進行當前vue實例的渲染,在渲染過程中會創(chuàng)建vNode,進而訪問數(shù)據(jù)data中的屬性,進入到get方法中,觸發(fā)dep.depend()。
4、dep.depend
dep.depend()是在訪問obj[key]的時候進行執(zhí)行的,在渲染過程中Dep.target就是渲染watcher,條件滿足,執(zhí)行Dep.target.addDep(this),即執(zhí)行watcher中的
/**
* Add a dependency to this directive.
*/
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)) {
dep.addSub(this)
}
}
}
newDepIds和depIds分別表示當前訂閱者依賴的當前發(fā)布者和舊發(fā)布者id的Set集合,newDeps表示當前發(fā)布者實例的數(shù)組列表。首次渲染時this.newDepIds中不包含id,this.newDepIds添加了發(fā)布者的id,this.newDeps中添加了dep實例。同時,this.depIds中不包含id,繼而執(zhí)行到dep.addSub(this)。
addSub (sub: Watcher) {
this.subs.push(sub)
}
這個動作就表示訂閱者watcher訂閱了發(fā)布者dep發(fā)布的消息,當前發(fā)布者的subs數(shù)組中訂閱者數(shù)量+1,等下次數(shù)據(jù)變化時發(fā)布者就通過dep.notify()的方式進行消息通知。
5、dep.notify
notify () {
// stabilize the subscriber list first
const subs = this.subs.slice()
if (process.env.NODE_ENV !== 'production' && !config.async) {
// subs aren't sorted in scheduler if not running async
// we need to sort them now to make sure they fire in correct
// order
subs.sort((a, b) => a.id - b.id)
}
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
const subs = this.subs.slice()對訂閱者進行淺拷貝,subs.sort((a, b) => a.id - b.id)按照訂閱者的id進行排序,最后循環(huán)訂閱者,訂閱者觸發(fā)update方法:
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
}
this.dirty表示計算屬性,這里是false,this.sync表示同步,這里是false,最后會走到queueWatcher(this):
/**
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
*/
export function queueWatcher (watcher: Watcher) {
const id = watcher.id
if (has[id] == null) {
has[id] = true
if (!flushing) {
queue.push(watcher)
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
let i = queue.length - 1
while (i > index && queue[i].id > watcher.id) {
i--
}
queue.splice(i + 1, 0, watcher)
}
// queue the flush
if (!waiting) {
waiting = true
if (process.env.NODE_ENV !== 'production' && !config.async) {
flushSchedulerQueue()
return
}
nextTick(flushSchedulerQueue)
}
}
}
這里未刷新狀態(tài)flushing === false時會在隊列queue中推入訂閱者watcher,如果沒有在等待狀態(tài)waiting===false時執(zhí)行nextTick將flushSchedulerQueue的執(zhí)行推入異步隊列中,等待所有的同步操作執(zhí)行完畢再去按照次序執(zhí)行異步的flushSchedulerQueue。需要了解nextTick原理請移步:http://www.dbjr.com.cn/article/261842.htm
/**
* Flush both queues and run the watchers.
*/
function flushSchedulerQueue () {
currentFlushTimestamp = getNow()
flushing = true
let watcher, id
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
queue.sort((a, b) => a.id - b.id)
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
watcher = queue[index]
if (watcher.before) {
watcher.before()
}
id = watcher.id
has[id] = null
watcher.run()
// in dev build, check and stop circular updates.
if (process.env.NODE_ENV !== 'production' && has[id] != null) {
circular[id] = (circular[id] || 0) + 1
if (circular[id] > MAX_UPDATE_COUNT) {
warn(
'You may have an infinite update loop ' + (
watcher.user
? `in watcher with expression "${watcher.expression}"`
: `in a component render function.`
),
watcher.vm
)
break
}
}
}
// keep copies of post queues before resetting state
const activatedQueue = activatedChildren.slice()
const updatedQueue = queue.slice()
resetSchedulerState()
// call component updated and activated hooks
callActivatedHooks(activatedQueue)
callUpdatedHooks(updatedQueue)
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush')
}
}
function callUpdatedHooks (queue) {
let i = queue.length
while (i--) {
const watcher = queue[i]
const vm = watcher.vm
if (vm._watcher === watcher && vm._isMounted && !vm._isDestroyed) {
callHook(vm, 'updated')
}
}
}
這里主要做了四件事:
- 對隊列
queue進行排序 - 遍歷執(zhí)行
watcher的run方法 resetSchedulerState進行重置,清空queue,并且waiting = flushing = false進行狀態(tài)重置callUpdatedHooks執(zhí)行callHook(vm, 'updated')生命周期鉤子函數(shù) 這里的run是在Watcher的時候定義的:
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
run () {
if (this.active) {
const value = this.get()
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) ||
this.deep
) {
// set new value
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)
}
}
}
}
active默認為true,執(zhí)行到const value = this.get()就開始了數(shù)據(jù)變化后的渲染的操作,好比訂閱者收到報紙后認真讀報一樣。get方法中,value = this.getter.call(vm, vm)渲染執(zhí)行完以后,會通過popTarget把targetStack棧頂?shù)脑匾瞥?,并且通過Dep.target = targetStack[targetStack.length - 1]修改當前執(zhí)行的元素。最后執(zhí)行this.cleanupDeps:
6、訂閱者取消訂閱
/**
* Clean up for dependency collection.
*/
cleanupDeps () {
let i = this.deps.length
while (i--) {
const dep = this.deps[i]
if (!this.newDepIds.has(dep.id)) {
dep.removeSub(this)
}
}
let tmp = this.depIds
this.depIds = this.newDepIds
this.newDepIds = tmp
this.newDepIds.clear()
tmp = this.deps
this.deps = this.newDeps
this.newDeps = tmp
this.newDeps.length = 0
}
首先通過while的方式循環(huán)舊的this.deps發(fā)布者的數(shù)組,如果當前訂閱者所依賴的發(fā)布者this.newDepIds中沒有包含舊的發(fā)布者,那么,就讓發(fā)布者在this.subs中移除訂閱者,這樣就不會讓發(fā)布者dep進行額外的通知,這種額外的通知可能會引起未訂閱者的行為(可能消耗內(nèi)存資源或引起不必要的計算)。后面的邏輯就是讓新舊發(fā)布者id和dep進行交換,方便下次發(fā)布者發(fā)布消息后的清除操作。
小結(jié)
vue中的發(fā)布訂閱者是在借助Object.defineProperty將數(shù)據(jù)變成響應式的過程中定義了dep,在get過程中dep對于訂閱者的加入進行處理,在set修改數(shù)據(jù)的過程中dep通知訂閱者進行相應的操作。
以上就是vue2從數(shù)據(jù)變化到視圖變化發(fā)布訂閱模式詳解的詳細內(nèi)容,更多關于vue2數(shù)據(jù)視圖變化發(fā)布訂閱模式的資料請關注腳本之家其它相關文章!
相關文章
vue awesome swiper異步加載數(shù)據(jù)出現(xiàn)的bug問題
這篇文章主要介紹了vue awesome swiper異步加載數(shù)據(jù)出現(xiàn)的bug問題,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-07-07
解決VUE中document.body.scrollTop為0的問題
今天小編就為大家分享一篇解決VUE中document.body.scrollTop為0的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09
Vue router-view和router-link的實現(xiàn)原理
這篇文章主要介紹了Vue router-view和router-link的實現(xiàn)原理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03

