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

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

  1. Vue源码学习之Computed与Watcher原理

    前言  computed与watch是我们在vue中常用的操作,computed是一个惰性求值观察者,具有缓存性,只有当依赖发生变化,第一次访问computed属性,才会计算新的值.而watch则是当 ...

  2. 源码解读_入口开始解读Vue源码系列(二)——new Vue 的故事

    作者:muwoo 转发链接:https://github.com/muwoo/blogs/blob/master/src/Vue/2.md 目录 入口开始解读Vue源码系列(一)--造物创世 入口开始 ...

  3. Vue响应式原理 vue源码(十一)

    前言 看过很多讲响应式的文章,大多都是告诉你们,有Observer,Dep,Wathcer类,Object.definePorperty,先会触发get中的dep.depend收集依赖,然后数据改变时 ...

  4. Vue源码--解读vue响应式原理

    原文链接:https://geniuspeng.github.io/2018/01/05/vue-reactivity/ Vue的官方说明里有深入响应式原理这一节.在此官方也提到过: 当你把一个普通的 ...

  5. 【Vue原理】Vue源码阅读总结大会

    专注 Vue 源码分享,为了方便大家理解,分为了白话版和 源码版,白话版可以轻松理解工作原理和设计思想,源码版可以更清楚内部操作和 Vue的美,喜欢我就关注我的公众号,好吧兄弟,不会让你失望的 阅读源 ...

  6. 【Vue原理】Vue源码阅读总结大会 - 序

    [Vue原理]Vue源码阅读总结大会 - 序 阅读源码准备了什么 1.掌握 Vue 所有API 2.JavaScript 扎实基础 3.看完 JavaScript 设计模式 4.学会调试 Vue 源码 ...

  7. [Vue源码分析]自定义事件原理及事件总线的实现

    最近小组有个关于vue源码分析的分享会,提前准备一下- 前言: 我们都知道Vue中父组件可以通过 props 向下传数据给子组件:子组件可以通过向$emit触发一个事件,在父组件中执行回调函数,从而实 ...

  8. [Vue源码分析] v-model实现原理

    最近小组有个关于vue源码分析的分享会,提前准备一下- 前言: 我们都知道使用v-model可以实现数据的双向绑定,及实现数据的变化驱动dom的更新,dom的更新影响数据的变化.那么v-model是怎 ...

  9. vue 源码自问自答-响应式原理

    vue 源码自问自答-响应式原理 最近看了 Vue 源码和源码分析类的文章,感觉明白了很多,但是仔细想想却说不出个所以然. 所以打算把自己掌握的知识,试着组织成自己的语言表达出来 不打算平铺直叙的写清 ...

最新文章

  1. 游戏数据的捕捉(郁金香学习笔记)
  2. 将x的二进制最后一位置为0
  3. 数据仓库组件:HBase集群环境搭建和应用案例
  4. java开发汉字显示不全_求java转码ISO-8859-1转UTF-8汉字显示不全补救方案?
  5. 47 - 算法 - 记住常用位运算-Leetcode-136-只出现一次的数字
  6. Python基础(2):控制结构
  7. 免费语音识别_免费 语音识别_免费语音识别api - 云+社区 - 腾讯云
  8. 阶段3 2.Spring_03.Spring的 IOC 和 DI_4 ApplicationContext的三个实现类
  9. 光储直流微电网simulink仿真模型
  10. GitChat · 前端 | 从软件工程角度看大前端技术栈
  11. 城市信息学其五-空间经济学、城市信息学、和交通便利
  12. 模拟退火算法解决车间工作台工作指派问题
  13. 企业OA办公系统选型技巧实用指南
  14. python color 颜色名称对照
  15. 如何在批处理 bat cmd 运行时 延时 等待 ?
  16. 扫描普通二维码,进入微信小程序
  17. 今日头条有麻烦了!App 被下架
  18. PS 图像调整算法——饱和度调整
  19. 泛泰长短信修改教程(供其他泛泰机型参考)
  20. 电磁兼容(EMC)测试

热门文章

  1. 图像分割——基于二维灰度直方图的阈值处理
  2. python字符串转浮点数_如何在Python中检查字符串是否为数字(浮点数)?
  3. Java——IO流(序列流)
  4. SSH加密密码中的非对称式密码学
  5. C++ 文件读写操作01
  6. Epoll 的tcp通信代码(服务器+客户端)
  7. linux网络编程之posix 线程(三):posix 匿名信号量与互斥锁 示例生产者--消费者问题
  8. linux网络编程(一)网络基础传输知识
  9. Tomcat 学习笔记(0)
  10. 516. 最长回文子序列