您现在的位置是:网站首页> 编程资料编程资料

vue2从数据变化到视图变化发布订阅模式详解_vue.js_

2023-05-24 455人已围观

简介 vue2从数据变化到视图变化发布订阅模式详解_vue.js_

引言

发布订阅者模式是最常见的模式之一,它是一种一对多的对应关系,当一个对象发生变化时会通知依赖他的对象,接受到通知的对象会根据情况执行自己的行为。

假设有财经报纸送报员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打电话取消了订阅,如果不取消的话,积攒的报纸就会溢出小邮箱。
  • 有新的报社开业:有一天镇子又开了家体育类的报馆,送报员是sportDep,b和d也是球类爱好者,于是在sportDep那里做了登记,sportDep的记录中就有了b和d。
    从上面的例子中可以看出,刚开始送报员financialDep的记录中有a,b和c,先是d加进来后来是a离开,最终financialDep的记录中有b,c和d。体育类报馆开张的时候,b和d也订阅了报纸,sportDep的记录中就有了b和d。我们发现,c只订阅了财经类报刊,而b和d既订阅了财经类的报纸也定了财经类的报刊。

一、发布订阅者模式的特点

从以上例子可以发现特点:

  • 发布者可以支持订阅者的加入
  • 发布者可以支持订阅者的删除
  • 一个发布者可以有多个订阅者,一个订阅者也可以订阅多个发布者的消息那可能会有疑问,有没有可能会有发布者的删除,答案是会,但是此时,发布者已消失,订阅者再也不会收到消息,也就不会与当前发布者相关的消息诱发的行为。好比体育类报馆关停了(发布者删除)那么b和d在也不会收到体育类报纸(消息),也就不会再阅读体育类报纸(行为)。

二、vue中的发布订阅者模式

以上的例子基本就是vue中发布订阅者的大体概况,vue中的发布者是啥时候定义的?
new Vue实例化的过程中会执行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是函数又会执行getData方法。然后,获取methodsprops中的key值,如果已经定义过则在开发环境进行控制台警告。其中,proxy的目的是让访问this[key]相当于访问this._data[key]。最后,对数据进行响应式处理 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的实例,那么说明该值已经被响应式处理过,直接将value.__ob__赋值给ob并在最后返回即可。如果满足else if中的条件,则可执行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) { for (let i = 0, l = items.length; i < l; i++) { observe(items[i]) } } } 

Observer是构造函数,通过对value是否是数组的判断,分别执行observeArraywalkobserveArray会对数组中的元素执行observe(items[i]),即通过递归的方式对value树进行深度遍历,递归的最后都会执行到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订阅者收集、数据变化时发布者dep通知subs中订阅者watcher进行相应操作的主要流程,new Dep()实例化、Object.defineProperty方法、dep.depend()订阅者收集和dep.notify()是主要的功能。先看发布者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; 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就相当于财经或者体育报馆,其中定义了属性idsubs,subs相当于送报员financialDep手中的笔记本,用来是用来记录订阅者的数组。发布者的消息如何发给订阅者,就需要借助Object.defineProperty:

2、Object.defineProperty

对于一个对象的属性进行访问或者设置的时候可以为其设置getset方法,在其中进行相应的操作,这也是vue响应式原理的本质,也是IE低版本浏览器不支持vue框架的原因,因为IE低版本浏览器不支持Object.defineProperty方法。

Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { // 当访问属性的时候,进行订阅者的收集 }, set: function reactiveSetter (newVal) { // 当修改属性的时候,收到发布者消息的时候进行相应的操作 } }) 

在vue中订阅者有computer watcher计算属性、watch watcher侦听器和render watcher渲染watcher。这里先介绍渲染watcher:

3、watcher

let uid = 0 /** * A watcher parses an expression, 
                
                

-六神源码网