vue 数据劫持 响应式原理 Observer Dep Watcher
1、vue响应式原理流程图概览

2、具体流程
(1)vue示例初始化(源码位于instance/index.js)
import { initMixin } from './init'
import { stateMixin } from './state'
import { renderMixin } from './render'
import { eventsMixin } from './events'
import { lifecycleMixin } from './lifecycle'
import { warn } from '../util/index'
function Vue (options) {
if (process.env.NODE_ENV !== 'production' &&
!(this instanceof Vue)
) {
warn('Vue is a constructor and should be called with the `new` keyword')
}
this._init(options)
}
initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)
export default Vue
响应式相关的是“stateMixin”。
(2)、state.js(源码位于instance/state.js)
与响应式有关的是:
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 */)
}
在initData中实现了2个功能:
(2).1 将data中的对象代理(proxy)到_data上
说明proxy函数也是使用的Object.defineProperty,
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)
}
也就是说vm._data.变量都是响应式数据(即vm.变量)。
(2).2 将data中的数据变为响应式数据,即
// observe data
observe(data, true /* asRootData */)
(3)observe类
第(2)步的observe函数:
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
}
调用了Observer类:
现在看Observer的构造函数和walk方法:
constructor (value: any) {
this.value = value
this.dep = new Dep()
this.vmCount = 0
def(value, '__ob__', this)
if (Array.isArray(value)) {
const augment = hasProto
? protoAugment
: copyAugment
augment(value, arrayMethods, arrayKeys)
this.observeArray(value)
} else {
this.walk(value)
}
}
/**
* Walk through each property 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])
}
}
需要说明的是,并不是data中的所有数据都会变成响应式的。
请看例子:
new Vue({
template:
`<div>
<span>text1:</span> {{text1}}
<span>text2:</span> {{text2}}
<div>`,
data: {
text1: 'text1',
text2: 'text2',
text3: 'text3'
}
});
data中text3并没有被模板实际用到,为了提高代码执行效率,我们没有必要对其进行响应式处理,因此,依赖收集简单点理解就是收集只在实际页面中用到的data数据,即text1和text2。
2019.3.8 修正

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()
}
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
dep.notify()
}
defineReactive函数中会用到Dep类来收集依赖(dep.depend())以及当数据变化时触发更新(dep.notify())。
(4)Dep类
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()
}
}
}
Dep类的构造函数中的subs是Watcher(观察者)类。vue实例中data的一个值,可以添加多个Watcher,同时这个值变化的时候也是触发这多个Watcher的更新。
(5)Watcher类
Watcher类主要用来收集依赖和触发更新。
Watcher类也是实现了$watch(),即:https://cn.vuejs.org/v2/api/#watch
(6)Observer、Dep和Watcher类关系

Observer类是书店(vue实例的data对象),里面有好多书(Dep类),每本书可以被订阅(Watcher类)。
当某一本书更新时,订阅的Watcher类会收到通知,进而更新书店内容(vue实例的data对象)。
Dep类是Observer类和Watcher类链接的桥梁。
vue 数据劫持 响应式原理 Observer Dep Watcher的更多相关文章
- Vue数据绑定和响应式原理
Vue数据绑定和响应式原理 当实例化一个Vue构造函数,会执行 Vue 的 init 方法,在 init 方法中主要执行三部分内容,一是初始化环境变量,而是处理 Vue 组件数据,三是解析挂载组件.以 ...
- Vue 2.0 与 Vue 3.0 响应式原理比较
Vue 2.0 的响应式是基于Object.defineProperty实现的 当你把一个普通的 JavaScript 对象传入 Vue 实例作为 data 选项,Vue 将遍历此对象所有的 prop ...
- 手写实现vue的MVVM响应式原理
文中应用到的数据名词: MVVM ------------------ 视图-----模型----视图模型 三者与 Vue 的对应:view 对应 te ...
- 学习 vue 源码 -- 响应式原理
概述 由于刚开始学习 vue 源码,而且水平有限,有理解或表述的不对的地方,还请不吝指教. vue 主要通过 Watcher.Dep 和 Observer 三个类来实现响应式视图.另外还有一个 sch ...
- vue学习之响应式原理的demo实现
Vue.js 核心: 1.响应式的数据绑定系统 2.组件系统. 访问器属性 访问器属性是对象中的一种特殊属性,它不能直接在对象中设置,而必须通过 defineProperty() 方法单独定义. va ...
- vue核心之响应式原理(双向绑定/数据驱动)
实例化一个vue对象时, Observer类将每个目标对象(即data)的键值转换成getter/setter形式,用于进行依赖收集以及调度更新. Observer src/core/observer ...
- vue2双向绑定原理:深入响应式原理defineProperty、watcher、get、set
响应式是什么?Vue 最独特的特性之一- 就是我们在页面开发时,修改data值的时候,数据.视图页面需要变化的地方变化. 主要使用到哪些方法? 用 Object.defineProperty给watc ...
- Vue.js响应式原理
写在前面 因为对Vue.js很感兴趣,而且平时工作的技术栈也是Vue.js,这几个月花了些时间研究学习了一下Vue.js源码,并做了总结与输出. 文章的原地址:answershuto/learnV ...
- Vue 数据响应式原理
Vue 数据响应式原理 Vue.js 的核心包括一套“响应式系统”.“响应式”,是指当数据改变后,Vue 会通知到使用该数据的代码.例如,视图渲染中使用了数据,数据改变后,视图也会自动更新. 举个简单 ...
随机推荐
- IPHONE IOS6 模拟器没有HOME按键解决方法
替代home键的快捷键是 Cmd-Shift-H: 双击HOME键就是 Cmd-Shift-H 按两次: 参考:http://www.cnblogs.com/yingkong1987/archive/ ...
- #pragma mark 添加分割线 及 其它类似标记 - 转
#pragma marks Comments containing: MARK: TODO: FIXME: !!!: ???: 除了使用 #pragma mark -添加分割线之外, 以上几种标记均可 ...
- java线程的一些基础小知识
--------------------------------------------------------------------------------------------------线程 ...
- pytest文档23-使用多个fixture和fixture直接互相调用
使用多个fixture 如果用例需要用到多个fixture的返回数据,fixture也可以return一个元组.list或字典,然后从里面取出对应数据. # test_fixture4.py impo ...
- cocos编译Android版本号问题总结
今天编译cocos2d-x项目到Android平台遇到编译不通过的问题,编译错误提示是一堆乱码. 主要原因有: 1.文件编码格式错误 或 换行符格式错误,改动方法为,在VS2012里面选择 文件-&g ...
- 开篇-QT完全手册
嵌入式工具Qt的安装与使用 摘要 Qt是Trolltech公司的一个产品.Trolltech是挪威的一家软件公司,主要开 发两种产品:一种是跨平台应用程序界面框架:另外一种就是提供给做嵌入式Linux ...
- 【BZOJ】【2434】【NOI2011】阿狸的打字机
AC自动机+DFS序+BIT 好题啊……orz PoPoQQQ 大爷 一道相似的题目:[BZOJ][3172][TJOI2013]单词 那道题也是在fail树上数有多少个点,只不过这题是在x的fail ...
- Informatica 常用组件Lookup缓存之三 重建查找高速缓存
如果您认为查找源在 PowerCenter 上次构建高速缓存时已更改,则可指示 PowerCenter 重建查找高速缓存. 重建高速缓存时,PowerCenter 会覆盖现有永久高速缓存文件而创建新的 ...
- 什么是Copy-Only Backup? 为什么要用它?
Copy-only backup是一种独立于传统SQL Backup方法的一种备份方式. 一般来说, 做一次数据库备份会影响到后面的备份和还原作业. 然而, 有时你需要为了某个特殊的目的而做一次备份但 ...
- JavaScript初学者建议:不要去管浏览器兼容
如果可以回到过去的话,我会告诉自己这句话:"初学JavaScript的时候无视DOM和BOM的兼容性" 我初学时的处境 在我初学JavaScript的时候最头痛的就是浏览器兼容问题 ...