Vue源码: 关于vm.$watch()内部原理

vm.$watch()用法

关于vm.$watch()详细用法可以见官网。

大致用法如下:

<script>const app = new Vue({el: "#app",data: {a: {b: {c: 'c'}}},mounted () {this.$watch(function () {return this.a.b.c}, this.handle, {deep: true,immediate: true // 默认会初始化执行一次handle})},methods: {handle (newVal, oldVal) {console.log(this.a)console.log(newVal, oldVal)},changeValue () {this.a.b.c = 'change'}}})
</script>
复制代码

可以看到data属性整个a对象被Observe, 只要被Observe就会有一个__ob__标示(即Observe实例), 可以看到__ob__里面有dep,前面讲过依赖(dep)都是存在Observe实例里面, subs存储的就是对应属性的依赖(Watcher)。 好了回到正文, vm.$watch()在源码内部如果实现的。

内部实现原理

// 判断是否是对象
export function isPlainObject (obj: any): boolean {return _toString.call(obj) === '[object Object]'
}复制代码

源码位置: vue/src/core/instance/state.js

// $watch 方法允许我们观察数据对象的某个属性,当属性变化时执行回调
// 接受三个参数: expOrFn(要观测的属性), cb, options(可选的配置对象)
// cb即可以是一个回调函数, 也可以是一个纯对象(这个对象要包含handle属性。)
// options: {deep, immediate}, deep指的是深度观测, immediate立即执行回掉
// $watch()本质还是创建一个Watcher实例对象。Vue.prototype.$watch = function (expOrFn: string | Function,cb: any,options?: Object): Function {// vm指向当前Vue实例对象const vm: Component = thisif (isPlainObject(cb)) {// 如果cb是一个纯对象return createWatcher(vm, expOrFn, cb, options)}// 获取optionsoptions = options || {}// 设置user: true, 标示这个是由用户自己创建的。options.user = true// 创建一个Watcher实例const watcher = new Watcher(vm, expOrFn, cb, options)if (options.immediate) {// 如果immediate为真, 马上执行一次回调。try {// 此时只有新值, 没有旧值, 在上面截图可以看到undefined。// 至于这个新值为什么通过watcher.value, 看下面我贴的代码cb.call(vm, watcher.value)} catch (error) {handleError(error, vm, `callback for immediate watcher "${watcher.expression}"`)}}// 返回一个函数,这个函数的执行会解除当前观察者对属性的观察return function unwatchFn () {// 执行teardown()watcher.teardown()}}
复制代码

关于watcher.js。

源码路径: vue/src/core/observer/watcher.js

export default class Watcher {vm: Component;expression: string;cb: Function;id: number;deep: boolean;user: boolean;lazy: boolean;sync: boolean;dirty: boolean;active: boolean;deps: Array<Dep>;newDeps: Array<Dep>;depIds: SimpleSet;newDepIds: SimpleSet;before: ?Function;getter: Function;value: any;constructor (vm: Component, // 组件实例对象expOrFn: string | Function, // 要观察的表达式cb: Function, // 当观察的表达式值变化时候执行的回调options?: ?Object, // 给当前观察者对象的选项isRenderWatcher?: boolean // 标识该观察者实例是否是渲染函数的观察者) {// 每一个观察者实例对象都有一个 vm 实例属性,该属性指明了这个观察者是属于哪一个组件的this.vm = vmif (isRenderWatcher) {// 只有在 mountComponent 函数中创建渲染函数观察者时这个参数为真// 组件实例的 _watcher 属性的值引用着该组件的渲染函数观察者vm._watcher = this}vm._watchers.push(this)// options// deep: 当前观察者实例对象是否是深度观测// 平时在使用 Vue 的 watch 选项或者 vm.$watch 函数去观测某个数据时,// 可以通过设置 deep 选项的值为 true 来深度观测该数据。// user: 用来标识当前观察者实例对象是 开发者定义的 还是 内部定义的// 无论是 Vue 的 watch 选项还是 vm.$watch 函数,他们的实现都是通过实例化 Watcher 类完成的// sync: 告诉观察者当数据变化时是否同步求值并执行回调// before: 可以理解为 Watcher 实例的钩子,当数据变化之后,触发更新之前,// 调用在创建渲染函数的观察者实例对象时传递的 before 选项。if (options) {this.deep = !!options.deepthis.user = !!options.userthis.lazy = !!options.lazythis.sync = !!options.syncthis.before = options.before} else {this.deep = this.user = this.lazy = this.sync = false}// cb: 回调this.cb = cbthis.id = ++uid // uid for batchingthis.active = true// 避免收集重复依赖,且移除无用依赖this.dirty = this.lazy // for lazy watchersthis.deps = []this.newDeps = []this.depIds = new Set()this.newDepIds = new Set()this.expression = process.env.NODE_ENV !== 'production'? expOrFn.toString(): ''// 检测了 expOrFn 的类型// this.getter 函数终将会是一个函数if (typeof expOrFn === 'function') {this.getter = expOrFn} else {this.getter = parsePath(expOrFn)if (!this.getter) {this.getter = noopprocess.env.NODE_ENV !== 'production' && warn(`Failed watching path: "${expOrFn}" ` +'Watcher only accepts simple dot-delimited paths. ' +'For full control, use a function instead.',vm)}}// 求值this.value = this.lazy? undefined: this.get()}/*** 求值: 收集依赖* 求值的目的有两个* 第一个是能够触发访问器属性的 get 拦截器函数* 第二个是能够获得被观察目标的值*/get () {// 推送当前Watcher实例到Dep.targetpushTarget(this)let value// 缓存vmconst vm = this.vmtry {// 获取valuevalue = 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 watchingif (this.deep) {// 递归地读取被观察属性的所有子属性的值// 这样被观察属性的所有子属性都将会收集到观察者,从而达到深度观测的目的。traverse(value)}popTarget()this.cleanupDeps()}return value}/*** 记录自己都订阅过哪些Dep*/addDep (dep: Dep) {const id = dep.id// newDepIds: 避免在一次求值的过程中收集重复的依赖if (!this.newDepIds.has(id)) {this.newDepIds.add(id) // 记录当前watch订阅这个depthis.newDeps.push(dep) // 记录自己订阅了哪些depif (!this.depIds.has(id)) {// 把自己订阅到depdep.addSub(this)}}}/*** Clean up for dependency collection.*/cleanupDeps () {let i = this.deps.lengthwhile (i--) {const dep = this.deps[i]if (!this.newDepIds.has(dep.id)) {dep.removeSub(this)}}//newDepIds 属性和 newDeps 属性被清空// 并且在被清空之前把值分别赋给了 depIds 属性和 deps 属性// 这两个属性将会用在下一次求值时避免依赖的重复收集。let tmp = this.depIdsthis.depIds = this.newDepIdsthis.newDepIds = tmpthis.newDepIds.clear()tmp = this.depsthis.deps = this.newDepsthis.newDeps = tmpthis.newDeps.length = 0}/*** Subscriber interface.* Will be called when a dependency changes.*/update () {/* istanbul ignore else */if (this.lazy) {this.dirty = true} else if (this.sync) {// 指定同步更新this.run()} else {// 异步更新队列queueWatcher(this)}}/*** Scheduler job interface.* Will be called by the scheduler.*/run () {if (this.active) {const value = this.get()// 对比新值 value 和旧值 this.value 是否相等// 是对象的话即使值不变(引用不变)也需要执行回调// 深度观测也要执行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 valueconst oldValue = this.valuethis.value = valueif (this.user) {// 意味着这个观察者是开发者定义的,所谓开发者定义的是指那些通过 watch 选项或 $watch 函数定义的观察者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)}}}}/*** Evaluate the value of the watcher.* This only gets called for lazy watchers.*/evaluate () {this.value = this.get()this.dirty = false}/*** Depend on all deps collected by this watcher.*/depend () {let i = this.deps.lengthwhile (i--) {this.deps[i].depend()}}/*** 把Watcher实例从从当前正在观测的状态的依赖列表中移除*/teardown () {if (this.active) {// 该观察者是否激活状态 if (!this.vm._isBeingDestroyed) {// _isBeingDestroyed一个标识,为真说明该组件实例已经被销毁了,为假说明该组件还没有被销毁// 将当前观察者实例从组件实例对象的 vm._watchers 数组中移除remove(this.vm._watchers, this)}// 当一个属性与一个观察者建立联系之后,属性的 Dep 实例对象会收集到该观察者对象let i = this.deps.lengthwhile (i--) {this.deps[i].removeSub(this)}// 非激活状态this.active = false}}
}
复制代码
export const unicodeRegExp = /a-zA-Z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD/
const bailRE = new RegExp(`[^${unicodeRegExp.source}.$_\\d]`)
// path为keypath(属性路径) 处理'a.b.c'(即vm.a.b.c) => a[b[c]]
export function parsePath (path: string): any {if (bailRE.test(path)) {return}const segments = path.split('.')return function (obj) {for (let i = 0; i < segments.length; i++) {if (!obj) returnobj = obj[segments[i]]}return obj}
}复制代码

转载于:https://juejin.im/post/5cbf2d3bf265da03b858510c

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/387778.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

docker启动顺序

VMDocker: 用户名:root 密码:XXXXXXXXXXXXX docker run -i -t -d -p 8081:8080 -p 23:22 67591570dd29 /bin/bash 常用命令 启动停止: service docker start service docker stop 所有镜像:docker images 当前执行:docker ps 提交保存docker容器: docker commit 进入到对应服…

js时钟倒计时

JS倒计时Date 代码如下&#xff1a; 1 <style type"text/css">2 * {3 margin: 0;4 padding: 0;5 }6 7 #box {8 border: 1px solid cyan;9 background-color: #000; 10 height: 50px; 11 width: 500px; 12 margin: 100px auto 0; 13 border-radius: 20px; 14 te…

JAVA的值传递问题

为什么 Java 中只有值传递&#xff1f; 首先回顾一下在程序设计语言中有关将参数传递给方法&#xff08;或函数&#xff09;的一些专业术语。按值调用(call by value)表示方法接收的是调用者提供的值&#xff0c;而按引用调用&#xff08;call by reference)表示方法接收的是调…

小程序如何封装自定义组件(Toast)

1、创建和pages 同级的component目录新建一个myToast目录 例如: 2、myToast.wxml文件内容: <!-- 自定义toast组件 --> <!-- name 模块名称 --><template name"toast" ><!-- catchtouchmove‘xxx’ 遮罩层的滚动穿透 --><!-- isHide 显示…

2017 百度杯丶二月场第一周WP

1.祸起北荒 题目&#xff1a; 亿万年前 天子之子华夜&#xff0c;被父神之神末渊上神告知六荒十海之北荒西二旗即将发生一场“百度杯”的诸神之战 他作为天族的太子必须参与到此次诸神之战定六荒十海 华夜临危受命&#xff0c;马上带着火凤凰飞行到北荒“西二旗” 却没想到这六…

docker保存对容器的修改

Docker 子命令: attach commit diff export history import insert kill login port pull restart rmi save start tag version build cp events help images info inspect load logs ps …

中国涉5.9亿份简历信息泄露

据美国科技媒体ZDNet报道&#xff0c;有研究人员发现&#xff0c;中国企业今年前3个月出现数起简历信息泄漏事故&#xff0c;涉及5.9亿份简历。大多数简历之所以泄露&#xff0c;主要是因为MongoDB和ElasticSearch服务器安全措施不到位&#xff0c;不需要密码就能在网上看到信息…

阿里云亮相2019联通合作伙伴大会,边缘计算等3款云产品助力5G时代产业数字化转型...

4月23日&#xff0c;2019中国联通合作伙伴大会在上海正式开幕&#xff0c;本次大会以“合作不设限&#xff0c;共筑新生态”为主题&#xff0c;涉及5G、边缘计算、云计算、物联网、新媒体、人工智能、互联网化等各领域超过600家合作伙伴与3万名各行业观众参会。据了解&#xff…

hadoop2.7 伪分布

hadoop 2.7.3伪分布式环境运行官方wordcounthadoop 2.7.3伪分布式模式运行wordcount 基本环境&#xff1a; 系统&#xff1a;win7 虚机环境&#xff1a;virtualBox 虚机&#xff1a;centos 7 hadoop版本&#xff1a;2.7.3 本次以伪分布式模式来运行wordcount。 参考&#xff1a…

iPhone手机屏幕尺寸(分辨率)

第一代iPhone2G屏幕为3.5英吋&#xff0c;分辨率为320*480像素&#xff0c;比例为3:2。 第二代iPhone3G屏幕为3.5英吋&#xff0c;分辨率为320*480像素&#xff0c;比例为3:2。 第三代iPhone3GS屏幕为3.5英吋&#xff0c;分辨率为320*480像素&#xff0c;比例为3:2。 第四代iPh…

[Java in NetBeans] Lesson 06. Custom classes

这个课程的参考视频和图片来自youtube。 主要学到的知识点有&#xff1a; Constructors: A special method called when an object of the class is createdproperty pattern and encapsulation(封装): hide the implementation details from the user, so when the class is b…

UDP打洞NAT大致分为下面四类 P2P

NAT大致分为下面四类 1) Full Cone 这种NAT内部的机器A连接过外网机器C后,NAT会打开一个端口.然后外网的任何发到这个打开的端口的UDP数据报都可以到达A.不管是不是C发过来的. 例如 A:192.168.8.100 NAT:202.100.100.100 C:292.88.88.88 A(192.168.8.100:5000) -> NAT(202.1…

让内核突破512字节的限制

转载于:https://www.cnblogs.com/ZHONGZHENHUA/p/10124237.html

高频算法面试题(字符串) 242. 有效的字母异位词

leetcode 242. 有效的字母异位词 给定两个字符串 s 和 t &#xff0c;编写一个函数来判断 t 是否是 s 的一个字母异位词。示例 1: 输入: s "anagram", t "nagaram" 输出: true 复制代码示例 2: 输入: s "rat", t "car" 输出: fals…

struts2的漏洞

文章前半部分来自团队小伙伴阿德马的总结&#xff0c;后半部分的Poc和Exp是小编匆忙之际借鉴而来&#xff0c;感谢写Poc和Exp的伙伴~ 安恒给官方上报的&#xff0c;然后官方选择了1个对国内来说比较敏感的时期发了公告出来&#xff0c;好蛋疼。 该漏洞的CVE编号是CVE-2017-56…

Java Statement PK PrepareStatement

PreparedStatement是用来执行SQL查询语句的API之一&#xff0c;Java提供了 Statement、PreparedStatement 和 CallableStatement三种方式来执行查询语句&#xff0c;其中 Statement 用于通用查询&#xff0c; PreparedStatement 用于执行参数化查询&#xff0c;而 CallableStat…

mysql在linux 下安装

安装环境&#xff1a;系统是 centos6.5 1、下载 下载地址&#xff1a;http://dev.mysql.com/downloads/mysql/5.6.html#downloads 下载版本&#xff1a;我这里选择的5.6.33&#xff0c;通用版&#xff0c;linux下64位 也可以直接复制64位的下载地址&#xff0c;通过命令下载&a…

Leetcode PHP题解--D47 868. Binary Gap

2019独角兽企业重金招聘Python工程师标准>>> D47 868. Binary Gap 题目链接 868. Binary Gap 题目分析 给定一个数字&#xff0c;计算其二进制表示中&#xff0c;出现的两个1最大距离。 思路 当然是先转换成二进制了。再进行遍历。 当只有一个1时&#xff0c;返回0。…

[洛谷P5048][Ynoi2019模拟赛]Yuno loves sqrt technology III

题目大意&#xff1a;有$n(n\leqslant5\times10^5)$个数&#xff0c;$m(m\leqslant5\times10^5)$个询问&#xff0c;每个询问问区间$[l,r]$中众数的出现次数 题解&#xff1a;分块&#xff0c;设块大小为$S$&#xff0c;先可以预处理出两两块之间的众数出现次数&#xff0c;复杂…