vue的依赖收集是定义在defineReactive方法中,通过Object.defineProperty来设置getter,红字部分主要做依赖收集,先判断了Dep.target如果有的情况会执行红字逻辑进行依赖收集过程

const getter = property && property.get
if (!getter && arguments.length === 2) {
val = obj[key]
}
const setter = property && property.set 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
},

Dep是一个类,target是Dep的一个静态属性,是一个Watcher,上面如果有target的话,会执行dep.depend方法,就是调用addDep方法

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()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}

addDep是定义值Watcher类下面的一个方法,通过一些逻辑判断是否存在,在执行上面Dep的addSub方法,将渲染watcher push 到subs数组里,然后我们看下是什么时候将Dep.tartget赋值的

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)
}
}
}

在我们调用mountComponent方法时,会实例化Watcher

export function mountComponent (
vm: Component,
el: ?Element,
hydrating?: boolean
): Component {
vm.$el = el
if (!vm.$options.render) {
vm.$options.render = createEmptyVNode
if (process.env.NODE_ENV !== 'production') {
/* istanbul ignore if */
if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
vm.$options.el || el) {
warn(
'You are using the runtime-only build of Vue where the template ' +
'compiler is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
)
} else {
warn(
'Failed to mount component: template or render function not defined.',
vm
)
}
}
}
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)
}
} // we set this to vm._watcher inside the watcher's constructor
// since the watcher's initial patch may call $forceUpdate (e.g. inside child
// component's mounted hook), which relies on vm._watcher being already defined
new Watcher(vm, updateComponent, noop, null, 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
}

在new  Watcher的过程中有一个get方法,会执行pushTargert方法

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
}

而pushTarget方法就是将当前的watcher 赋值给Dep.target

export function pushTarget (_target: ?Watcher) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = _target
}

Vue的派发更新,首先获取原有值和新值,然后对新值和旧值作对比,如果相同什么也不做,否则将新值赋值给val,如果新值仍然是个对象,则在重新调用observe方法将其变成响应式,最后调用dep.notify方法

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()
}

dep.notyify方法,就是遍历所有的订阅者,也就是渲染watcher,使每一个watcher调用update方法

notify () {
// stabilize the subscriber list first
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}

实际就是每个watcher执行queueWatcher()方法

update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
}

queueWatcher方法,先将watcher push到队列中,然后再下一个tick内执行flushSchedulerQueue,nextTick就是对promise的一层封装

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
nextTick(flushSchedulerQueue)

}
}
}

flushSchedulerQueue,首先对队列wacher进行排序,主要为了处理父子组件,userWatcher等情况,然后调用watcher.run方法

function flushSchedulerQueue () {
flushing = true
let watcher, id
queue.sort((a, b) => a.id - b.id)
for (index = 0; index < queue.length; index++) {
watcher = queue[index]
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
}
}
}

wathcer.run方法会将新值赋给value

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)
}
}
}
}

读Vue源码 (依赖收集与派发更新)的更多相关文章

  1. webpack源码-依赖收集

    webpack源码-依赖收集 version:3.12.0 程序主要流程: 触发make钩子 Compilation.js 执行EntryOptionPlugin 中注册的make钩子 执行compi ...

  2. 读 vue 源码一 (为什么this.message能够访问data里面的message)

    12月离职后,打算在年后再找工作了,最近陆陆续续的看了黄轶老师的vue源码解析,趁着还有几天过年时间记录一下. 目标:vue如何实现通过this.key,就能直接访问data,props,method ...

  3. 读Vue源码二 (响应式对象)

    vue在init的时候会执行observer方法,如果value是对象就直接返回,如果对象上没有定义过_ob_这个属性,就 new Observer实例 export function observe ...

  4. 【Vue源码学习】依赖收集

    前面我们学习了vue的响应式原理,我们知道了vue2底层是通过Object.defineProperty来实现数据响应式的,但是单有这个还不够,我们在data中定义的数据可能没有用于模版渲染,修改这些 ...

  5. Vue源码详细解析:transclude,compile,link,依赖,批处理...一网打尽,全解析!

    用了Vue很久了,最近决定系统性的看看Vue的源码,相信看源码的同学不在少数,但是看的时候却发现挺有难度,Vue虽然足够精简,但是怎么说现在也有10k行的代码量了,深入进去逐行查看的时候感觉内容庞杂并 ...

  6. 读懂源码:一步一步实现一个 Vue

    源码阅读:究竟怎样才算是读懂了? 市面上有很多源码分析的文章,就我看到的而言,基本的套路就是梳理流程,讲一讲每个模块的功能,整篇文章有一大半都是直接挂源码.我不禁怀疑,作者真的看懂了吗?为什么我看完后 ...

  7. Vue源码探究-数据绑定的实现

    Vue源码探究-数据绑定的实现 本篇代码位于vue/src/core/observer/ 在总结完数据绑定实现的逻辑架构一篇后,已经对Vue的数据观察系统的角色和各自的功能有了比较透彻的了解,这一篇继 ...

  8. 手牵手,从零学习Vue源码 系列二(变化侦测篇)

    系列文章: 手牵手,从零学习Vue源码 系列一(前言-目录篇) 手牵手,从零学习Vue源码 系列二(变化侦测篇) 陆续更新中... 预计八月中旬更新完毕. 1 概述 Vue最大的特点之一就是数据驱动视 ...

  9. Vue 源码解读(12)—— patch

    前言 前面我们说到,当组件更新时,实例化渲染 watcher 时传递的 updateComponent 方法会被执行: const updateComponent = () => { // 执行 ...

随机推荐

  1. 使用ElasticSearch全文检索以及集群部署

    ElasticSearch  即 ES 安装:版本---elasticsearch-2.4.6.tar.gz tar -zxvf elasticsearch-2.4.6.tar.gz 由于es不允许使 ...

  2. 如何使用mybatis插入数据之前就具生成id值

    SelectKey在Mybatis中是为了解决Insert数据时不支持主键自动生成的问题,该功能可以很随意的设置生成主键的方式. 不管SelectKey有多好,尽量不要遇到这种情况吧,毕竟很麻烦. k ...

  3. flink with rabbitmq,sink source mysql redis es

    flink-dockerhttps://github.com/melentye/flink-docker https://shekharsingh.com/blog/2016/11/12/apache ...

  4. Android的几种Manager

    电话管理器TelephoneManager 第一个实例是获取网络和SIM卡信息:界面是一个列表,这里省略,Java代码如下: public class MainActivity extends Act ...

  5. 2018-2019-2 网络对抗技术 20165317 Exp2 后门原理与实践

    2018-2019-2 网络对抗技术 20165317 Exp2 后门原理与实践 基础问题回答 例举你能想到的一个后门进入到你系统中的可能方式? 下载免费应用的时候会有绑定木马. 浏览某些网页时会有内 ...

  6. Linux 部署 xxl-job 注意问题

    问题:Failed to create parent directories for [/data/applogs/xxl-job/xxl-job-admin.log][原因:权限不足] 启动终端: ...

  7. [ionic3.x开发记录]ios下页面过渡效果不出现的小坑

    如果内容没有被<ion-content></ion-content>或者<ion-header></ion-header>标签包裹,页面过渡的时候是没有 ...

  8. JDK8 Stream操作整理

    1,forEach this.quoteItemList.forEach(p -> p.setMode(mode)); 2,获取对话属性,去重后生成集合 List<String> p ...

  9. 跨平台技术实践案例: 用 reactxp 重写墨刀的移动端

    Authors:  Gao Cong, Perry Poon Illustrators:  Shena Bian April 20, 2019 重新编写,又一次,我们又一次重新编写了移动端应用和移动端 ...

  10. 混合开发使用Chrome Inspect调试WebView预览手机界面和定位元素

    使用Chrome Inspect调试混合应用可以帮助我们排查问题.例如定位元素,快速修改CSS样式并实时查看效果.其实微信开发也是一种混合开发模式,微信可以看做一个原生的Android App搭配了一 ...