读Vue源码 (依赖收集与派发更新)

时间:2022-09-26 21:59:45

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&period;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源码详细解析&colon;transclude&comma;compile&comma;link&comma;依赖&comma;批处理&period;&period;&period;一网打尽,全解析&excl;

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

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

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

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

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

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

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

  9. 大白话Vue源码系列&lpar;01&rpar;:万事开头难

    阅读目录 Vue 的源码目录结构 预备知识 先捡软的捏 Angular 是 Google 亲儿子,React 是 Facebook 小正太,那咱为啥偏偏选择了 Vue 下手,一句话,Vue 是咱见过的 ...

随机推荐

  1. leetcode 题解:Binary Tree Inorder Traversal (二叉树的中序遍历)

    题目: Given a binary tree, return the inorder traversal of its nodes' values. For example:Given binary ...

  2. 关于ckeditor添加的class都会被清除掉的问题

    在源码中输入ul,并且带有class,然后点击源码,到可视化界面 结果显示为aaa,再点看源码,查看HTML源代码 解决方法: 添加配置 config.allowedContent = true 这个 ...

  3. 编译boost python模块遇到的错误:&period;&period;&sol;&period;&period;&sol;libraries&sol;boost&lowbar;1&lowbar;44&lowbar;0&sol;boost&sol;python&sol;detail&sol;wrap&lowbar;python&period;hpp&colon;75&colon;24&colon; fatal error&colon; patchlevel&period;h&colon; No such file or directory

    就是遇到类似标题上面的错误. 原因是没有安装对应python的python-dev依赖,不然编译到boost python模块的时候就会出错. 所以解决方案是sudo apt-get install ...

  4. 如何使用maven搭建web项目

    博客园注册了有二十多天了,还没有写过博客,今天就发一篇,也便于后面查找笔记. 我个人已经做了几年的java web开发了,由于所在的公司是业务型公司,用的都是一些老旧的稳定技术,很少接触到稍微新点的内 ...

  5. ZOJ - 2423-Fractal

    A fractal is an object or quantity that displays self-similarity, in a somewhat technical sense, on ...

  6. 如何在jsp中引入bootstrap

    如何在jsp中引入bootstrap包: 1.首先在http://getbootstrap.com/上下载Bootstrap的最新版. 您会看到两个按钮: Download Bootstrap:下载 ...

  7. LOJ6284 数列分块入门8(分块)

    两个锅 一个是sametag[i]==c 另一个是a[j]不要写成a[i] #include <cstdio> #include <cstring> #include < ...

  8. bzoj 1012&colon; &lbrack;JSOI2008&rsqb;最大数maxnumber &lpar;线段树)

    1012: [JSOI2008]最大数maxnumber Time Limit: 3 Sec  Memory Limit: 162 MBSubmit: 13081  Solved: 5654[Subm ...

  9. html-头标签的使用

    HTML两部分组成 head和body ** 在head里面的标签就是头标签 ** title标签:表示在标签上显示的内容 ** meta标签:设置页面的一些相关内容(用的比较少) <meta ...

  10. 解读:未来30年新兴科技趋势报告(AI Frist,IoT Second)

    前段时间美国公布的一份长达35页的<未来30年新兴科技趋势报告>.该报告是在美国过去五年内由*机构.咨询机构.智囊团.科研机构等发表的32份科技趋势相关研究调查报告的基础上提炼形成的. ...