众所周知:vue2.x是通过object.definePrototype来设置对象属性getter、setter来监听数据变化,那今天我们来研究一下vue的响应式原理,一步一步深入。
object.definePrototype
语法: Object.defineProperty(obj, prop, descriptor)
基础应用
/*
*params
obj 监听对象
prop 监听属性
descriptor 属性描述符
*/
let _obj = {
name: '小菜鸟'
},
tag = '老油条';
Object.defineProperty(_obj, 'name', {
get: () => {
console.log('触发getter');
return tag; // 这里返回的是tag变量
},
set: newVal => {
console.log("触发setter", newVal);
return newVal;
}
})
console.log(_obj.name); // 触发getter 老油条
_obj.name = '摸摸鱼' // 触发setter 摸摸鱼
通过上述代码,可以看到我们用Object.defineProperty方法监听了 _obj 的name属性,触发get,返回tag变量(老油条),触发set,返回newVal(摸摸鱼)。 Vue2.x 就是利用object.deineProperty这个api来拦截对象的get和set从而实现对象数据响应式。
Vue2.x的响应式就是在Observer中完成的,下面来探索下Observer
Observer 响应式
响应式过程
- 从 new Vue() 一文我们得知在 _init() 方法中会执行initState()方法;
- initState() 方法中会执行 initData()方法;
- initData 中调用 observe方法;
- observe 中实例化观察者(new Observer);
- Observer 实例化 调用 defineReactive 方法响应式对象;
// 1、 initState *src\core\instance\state.js
export function initState (vm: Component) {
vm._watchers = []
const opts = vm.$options
if (opts.props) initProps(vm, opts.props) // initProps
if (opts.methods) initMethods(vm, opts.methods) // initMethods
if (opts.data) { // 组件有data
initData(vm) // initData
} else {
observe(vm._data = {}, true /* asRootData */)
}
if (opts.computed) initComputed(vm, opts.computed)
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch) // initWatch
}
// 这里可以看出 props、methods、data、watch 优先级
}
// 2、 initData *src\core\instance\state.js
function initData (vm: Component) {
let data = vm.$options.data
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
// *** 中间过程省略
observe(data, true /* asRootData */) // observe data
}
// 3、 observe *src\core\observer\index.js
export function observe (value: any, asRootData: ?boolean): Observer | void {
// 如果不是对象或者虚拟dom返回
if (!isObject(value) || value instanceof VNode) {
return
}
let ob: Observer | void
// 判断是否有__ob__ 有的话说明数据已被观察 赋给返回值
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 // 不是vue实例
) {
ob = new Observer(value) // 实例观察者
}
if (asRootData && ob) {
ob.vmCount++
}
return ob
}
// 4、 Observer *src\core\observer\index.js
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 // 要被观察的value
this.dep = new Dep() // 创建一个依赖收集器
this.vmCount = 0
// 将该Observer实例,赋值给value的__ob__属性。
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方法
}
}
/**
* Walk through all properties and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
walk (obj: Object) { // 获取对象的键值组成的数组 遍历监视key
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])
}
}
}
// 5、 defineReactive *src\core\observer\index.js
export function defineReactive (
obj: Object,
key: string,
val: any,
customSetter?: ?Function,
shallow?: boolean
) {
const dep = new Dep()
// 获取对象属性描述符
const property = Object.getOwnPropertyDescriptor(obj, key)
// 属性描述符存在且configurable属性不可配置直接 return
if (property && property.configurable === false) {
return
}
// 属性描述符存在获取 getter、setter
const getter = property && property.get
const setter = property && property.set
// 没有 getter、setter 且参数长度是2 返回obj[key]
if ((!getter || setter) && arguments.length === 2) {
val = obj[key]
}
// 这里是一个递归处理,shallow标识是否深度处理该值。
// 意味着如果obj的key,对应的val还是对象,则使其也变成可观察的对象
let childOb = !shallow && observe(val)
// 监听对象key
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
// 在特定的时机进行依赖收集。通过Dep.target
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() // 触发更新
}
})
}
简述过程
// _init()方法中会执行initState()方法;
initState()
// initState()方法中会执行initData()方法;
function initState(vm){
let data = vn.$options.data;
initData(data)
}
// initData方法中调用observe
function initData(data) {
observe(data, true)
}
// observe中实例化 Observer
function observe() {
new Observer(value)
}
// Observer中 对象执行walk方法
class Observer{
this.walk(obj);
walk (obj) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i])
}
}
}
// defineReactive方法用来设置对象的属性描述符
function defineReactive(obj, key) {
const dep = new Dep()
// 省略部分代码
Object.defineProperty(obj, key, {
// 属性描述符
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
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
dep.notify() // 触发更新
}
})
}
// 上述可以了解到对象类型数据响应式过程
// 最终通过触发对象数据 get 收集依赖(dep.depend)、触发set调用dep.notify()实现数据视图响应式
至此实现了对象的响应式绑定
Dep 依赖管理
相信很多人对 Dep 这个概念不理解,Dep到底是用来做什么的?上面我们实现了对象的响应式绑定,可以监听到数据的变化了,那么我们如何更新视图呢,具体更新哪个地方呢?
Dep 可以理解成用来收集具体要更新到哪里的一个容器,在触发数据的 get 时,收集依赖 (watcher),改变数据时触发set,更新视图。
// *src\core\observer\dep.js
// 用于当作 Dep 的标识
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>;
// 定义一个 subs 数组,用来存放 watcher 实例
constructor () {
this.id = uid++
this.subs = []
}
// 将 watcher 实例添加到 subs 中
addSub (sub: Watcher) {
this.subs.push(sub)
}
// 从 subs 中移除对应的 watcher 实例。
removeSub (sub: Watcher) {
remove(this.subs, sub)
}
// 依赖收集,这就是上述看到的 dep.dpend 方法
depend () {
// Dep.target 是 watcher 实例
if (Dep.target) {
// 调用 watcher 实例的 addDep 方法,参数是当前 dep 实例
Dep.target.addDep(this)
}
}
// 派发更新,这就是我们之前看到的 dep.notify 方法
notify () {
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)
}
// 遍历 subs 数组,依次触发 watcher 实例的 update
for (let i = 0, l = subs.length; i < l; i++) {
// 调用 watcher 实例 update 方法
subs[i].update()
}
}
}
// 在 Dep 上挂一个静态属性 target,
// 这个 Dep.target 的值会在调用 pushTarget 和 popTarget 时被赋值,值为当前 watcher 实例对象。
Dep.target = null
// 维护一个栈结构,用于存储和删除 Dep.target
const targetStack = []
// pushTarget 会在 new Watcher 时被调用
export function pushTarget (_target: ?Watcher) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = _target
}
// popTarget 也会在 new Watcher 时被调用
export function popTarget () {
Dep.target = targetStack.pop()
}
通过阅读以上源码可知:Dep 是一个类,用于依赖收集和派发更新,也就是存放watcher实例和触发watcher实例update方法。
响应式总结
至此initData完结,上文中defineReactive 的 getter和setter的设定,在前期不会触发,因为这会还没有收集到依赖,这里只是把规则定好,真正用到的时候是在跟模板结合的时候。接下来我们看下挂载模板的地方。
// 贴一下_init方法的代码在巩固下初始过程 *src\core\instance\init.js
export function initMixin (Vue: Class<Component>) {
Vue.prototype._init = function (options?: Object) {
const vm: Component = this
// 省略 部分代码
vm._self = vm
initLifecycle(vm)
initEvents(vm)
initRender(vm)
callHook(vm, 'beforeCreate')
initInjections(vm)
initState(vm) // ***在此完成了对数据的响应式 但 此时还未收集到依赖
initProvide(vm)
callHook(vm, 'created')
// 省略部分代码
// 挂载阶段
if (vm.$options.el) {
vm.$mount(vm.$options.el) // ***真正收集依赖的时候在挂载阶段
}
}
}
$mount
Vue原型对$mount的定义有俩处,其实最终是调用第一处定义的mountComponent方法
// 第一处定义
// src\platforms\web\runtime\index.js
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && inBrowser ? query(el) : undefined
return mountComponent(this, el, hydrating)
}
// 第二处定义
// src\platforms\web\entry-runtime-with-compiler.js
var mount = Vue.prototype.$mount; // 第一处定义的$mount方法存下来
Vue.prototype.$mount = function (
el,
hydrating
) {
el = el && query(el); // query函数用来查找dom元素,这里就不贴了
// el不能是body,html
if (el === document.body || el === document.documentElement) {
warn(
"Do not mount Vue to <html> or <body> - mount to normal elements instead."
);
return this
}
var options = this.$options;
// 这里要判断初始化有无 render 函数
// render函数作用是返回 vnode
if (!options.render) {
var template = options.template;
// 没有template的情况
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template);
/* istanbul ignore if */
if (!template) {
warn(
("Template element not found or is empty: " + (options.template)),
this
);
}
}
} else if (template.nodeType) {
template = template.innerHTML;
} else {
{
warn('invalid template option:' + template, this);
}
return this
}
} else if (el) {
// 有el
template = getOuterHTML(el);
}
// 生成render函数
if (template) {
/* istanbul ignore if */
if (config.performance && mark) {
mark('compile');
}
var ref = compileToFunctions(template, {
outputSourceRange: "development" !== 'production',
shouldDecodeNewlines: shouldDecodeNewlines,
shouldDecodeNewlinesForHref: shouldDecodeNewlinesForHref,
delimiters: options.delimiters,
comments: options.comments
}, this);
var render = ref.render;
var staticRenderFns = ref.staticRenderFns;
options.render = render;
options.staticRenderFns = staticRenderFns;
/* istanbul ignore if */
if (config.performance && mark) {
mark('compile end');
measure(("vue " + (this._name) + " compile"), 'compile', 'compile end');
}
}
}
// ***********************************************************************
// 调用变量mount (实际是调用第一个定义的$mount方法 从而调用mountComponent方法)
return mount.call(this, el, hydrating)
};
mountComponent
// src\core\instance\lifecycle.js
export function mountComponent (
vm: Component,
el: ?Element,
hydrating?: boolean
): Component {
vm.$el = el
// 省略部分代码
callHook(vm, 'beforeMount')
let updateComponent
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
updateComponent = () => {
const name = vm._name
const id = vm._uid
const startTag = `vue-perf-start:${id}`
const endTag = `vue-perf-end:${id}`
mark(startTag)
const vnode = vm._render()
mark(endTag)
measure(`vue ${name} render`, startTag, endTag)
mark(startTag)
vm._update(vnode, hydrating)
mark(endTag)
measure(`vue ${name} patch`, startTag, endTag)
}
} else {
updateComponent = () => {
vm._update(vm._render(), hydrating) // ***更新视图核心***
// updateComponent调用vm._render()
// render函数核心是vnode = render.call(vm, vm.$createElement)
// _update负责把VNode渲染成⼀个真实的DOM并渲染
// render函数中会取读取vm.a的值。或读取vm.b的值。
// 当读取vm.a或者b的时候,就会触发对应属性的getter
// 然后会将当前的Watcher加入属性对应的dep中。
// 当触发属性的setter时,执行dep.notify(), 其实就是执行dep收集到的watcher挨个update
// update调用run方法.
// 而run方法又触发了当前的这个get方法,执行到getter.call的时候,界面就更新了。
}
}
// 核心 new Watcher 终于实例化了
new Watcher(vm, updateComponent, noop, { // updateComponent方法是重点
before () {
if (vm._isMounted && !vm._isDestroyed) {
callHook(vm, 'beforeUpdate')
}
}
}, true /* isRenderWatcher */)
hydrating = false
// manually mounted instance, call mounted on self
// mounted is called for render-created child components in its inserted hook
if (vm.$vnode == null) {
vm._isMounted = true
callHook(vm, 'mounted')
}
return vm
}
历尽千辛万苦,终于等到你,还好我没放弃
Watcher
Watcher 也是一个类,用于初始化 数据的 watcher实例。它的原型上有一个 update 方法,用于派发更新。
Watcher 源码较多,这里省略部分无关代码,想了解的可以看源码 src\core\observer\watcher.js
export default class Watcher {
constructor(
vm: Component,
expOrFn: string | Function,
cb: Function, // 回调函数
options?: ?Object,
isRenderWatcher?: boolean // 是否是渲染函数观察者,Vue 初始化时,这个参数被设为 true
) {
// 省略部分代码... 这里代码的作用是初始化一些变量
// expOrFn 可以是 字符串 或者 函数
// 什么时候会是字符串,例如我们正常使用的时候,watch: { x: fn }, Vue内部会将 `x` 这个key 转化为字符串
// 什么时候会是函数,其实 Vue 初始化时,就是传入的渲染函数 new Watcher(vm, updateComponent, noop, ...);
if (typeof expOrFn === 'function') {
this.getter = expOrFn
} else {
// 当watch形式 'a.b'的时候,就需要通过 parsePath 方法,parsePath 方法返回一个函数
// 函数内部会去获取 'a.b' 这个属性的值
this.getter = parsePath(expOrFn)
// 省略部分代码...
}
// 如果是计算属性,返回 undefined,否则通过get获取value
// 也就是在 new Watcher 时会调用 this.get()
this.value = this.lazy
? undefined
: this.get()
}
get () {
// 将 当前 watcher 实例,赋值给 Dep.target 静态属性
// 也就是说 执行了这行代码,Dep.target 的值就是 当前 watcher 实例
// 并将 Dep.target 入栈 ,存入 targetStack 数组中
pushTarget(this)
let value
const vm = this.vm
try {
// *** 此时this.getter 就是执行 updateComponent 方法
// 我们此时回过头 去看下 updateComponent 方法的注释
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() // Dep.target 出栈
this.cleanupDeps()
}
return value
}
// 这里再回顾一下
// dep.depend 方法,会执行 Dep.target.addDep(dep) 其实也就是 watcher.addDep(dep)
// watcher.addDep(dep) 会执行 dep.addSub(watcher)
// 将当前 watcher 实例 添加到 dep 的 subs 数组 中,也就是收集依赖
// dep.depend 和 这个 addDep 方法,有好几个 this, 可能有点绕。
addDep (dep: Dep) {
const id = dep.id
// 下面两个 if 条件都是去重的作用,我们可以暂时不考虑它们
// 只需要知道,这个方法 执行 了 dep.addSub(this)
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id)
this.newDeps.push(dep)
if (!this.depIds.has(id)) {
// 将当前 watcher 实例添加到 dep 的 subs 数组中
dep.addSub(this)
}
}
}
// 派发更新
update () {
if (this.lazy) {
this.dirty = true
// this.sync 为true,则立即执行 this.run
} else if (this.sync) {
this.run()
} else {
// 收集watcher到异步队列
queueWatcher(this)
}
}
run () {
if (this.active) {
const value = this.get() // 执行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) {
const info = `callback for watcher "${this.expression}"`
invokeWithErrorHandling(this.cb, this.vm, [value, oldValue], this.vm, info)
} else {
this.cb.call(this.vm, value, oldValue)
}
}
}
}
// 省略部分代码
}
总结
至此,我们了解到对象数据响应式的原理,以及data如何触发view更新的,核心就是object.definePrototype去拦截对象属性的get添加依赖,触发属性的set来更新依赖从而触发视图更新。更新视图的核心是vm._update(vm._render(), hydrating)。下一篇文章我们去了解下 vm._update 和 vm._render 原理。
如有错误烦请指出,一定第一时间学习更新。
至此我们还留下一个问题,那就是数组数据的响应式,这里就不赘述了,希望有兴趣的jym可以去了解一下。