您现在的位置: 365建站网 > 365文章 > vue.js中的watcher用法

vue.js中的watcher用法

文章来源:365jz.com     点击数:1217    更新时间:2018-11-03 16:38   参与评论


虽然计算属性在大多数情况下更合适,但有时也需要一个自定义的 watcher 。这是为什么 Vue 提供一个更通用的方法通过watch 选项,来响应数据的变化。当你想要在数据变化响应时,执行异步操作或开销较大的操作,这是很有用的。本文主要介绍了vue 中的 watcher的相关资料,需要的朋友可以参考下,希望能帮助到大家。


大家对于 watch 应该不陌生,项目中都用过下面这种写法:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

watch: {

 someProp () {

  // do something

 }

}

// 或者

watch: {

 someProp: {

  deep: true,

  handler () {

   // do something

  }

 }

}

上面的写法告诉 vue,我需要监听 someProp 属性的变化,于是 vue 在内部就会为我们创建一个 watcher 对象。(限于篇幅,我们不聊 watcher 的具体实现,感兴趣的可以直接看源码 watcher)

然而在 vue 中,watcher 的功能并没有这么单一,先上段代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

<template>

 <p>

  <p>a: {{ a }}</p>

  <p>b: {{ b }}</p>

  <button @click="increment">+</button>

 </p>

</template>

<script>

export default {

 data () {

  return {

   a: 1

  }

 },

 computed: {

  b () {

   return this.a * 2

  }

 },

 watch: {

  a () {

    console.log('a is changed')

  }

 },

 methods: {

  increment () {

   this.a += 1

  }

 },

 created () {

  console.log(this._watchers)

 }

}

</script>

在线demo

上面代码非常简单,我们现在主要关注 created 钩子中打印的 this._watchers,如下:

分别展开三个 watcher,观察每一个 expression,从上到下分别为:

1

2

3

b() {   return this.a * 2;↵  }

"a"

function () {   vm._update(vm._render(), hydrating);↵  }

上面三个 watcher 代表了三种不同功能的 watcher,我们将其按功能分为三类:

  • 在 watch 中定义的,用于监听属性变化的 watcher (第二个)

  • 用于 computed 属性的 watcher (第一个)

  • 用于页面更新的 watcher (第三个)

normal-watcher

我们在 watch 中定义的,都属于这种类型,即只要监听的属性改变了,都会触发定义好的回调函数

computed-watcher

每一个 computed 属性,最后都会生成一个对应的 watcher 对象,但是这类 watcher 有个特点,我们拿上面的 b 举例:

属性 b 依赖 a,当 a 改变的时候,b 并不会立即重新计算,只有之后其他地方需要读取 b 的时候,它才会真正计算,即具备 lazy(懒计算)特性

render-watcher

每一个组件都会有一个 render-watcher, function () {↵ vm._update(vm._render(), hydrating);↵ }, 当 data/computed

中的属性改变的时候,会调用该 render-watcher 来更新组件的视图

三种 watcher 的执行顺序

除了功能上的区别,这三种 watcher 也有固定的执行顺序,分别是:

1

computed-render -> normal-watcher -> render-watcher

这样安排是有原因的,这样就能尽可能的保证,在更新组件视图的时候,computed 属性已经是最新值了,如果 render-watcher 排在 computed-render 前面,就会导致页面更新的时候 computed 值为旧数据。

下面从一段实例代码中看下vue中的watcher

在这个示例中,使用 watch 选项允许我们执行异步操作(访问一个 API),限制我们执行该操作的频率,并在我们得到最终结果前,设置中间状态。这是计算属性无法做到的。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

<p id="watch-example">

<p>

Ask a yes/no question:

<input v-model="question">

</p>

<p>{{ answer }}</p>

</p>

<!-- Since there is already a rich ecosystem of ajax libraries -->

<!-- and collections of general-purpose utility methods, Vue core -->

<!-- is able to remain small by not reinventing them. This also -->

<!-- gives you the freedom to just use what you're familiar with. -->

<script src="https://unpkg.com/axios@0.12.0/dist/axios.min.js"></script>

<script src="https://unpkg.com/lodash@4.13.1/lodash.min.js"></script>

<script>

var watchExampleVM = new Vue({

el: '#watch-example',

data: {

question: '',

answer: 'I cannot give you an answer until you ask a question!'

},

watch: {

 // 如果 question 发生改变,这个函数就会运行

question: function (newQuestion) {

this.answer = 'Waiting for you to stop typing...'

this.getAnswer()

}

},

methods: {

 // _.debounce 是一个通过 lodash 限制操作频率的函数。

 // 在这个例子中,我们希望限制访问yesno.wtf/api的频率

 // ajax请求直到用户输入完毕才会发出

 // 学习更多关于 _.debounce function (and its cousin

// _.throttle), 参考: https://lodash.com/docs#debounce

getAnswer: _.debounce(

function () {

var vm = this

if (this.question.indexOf('?') === -1) {

vm.answer = 'Questions usually contain a question mark. ;-)'

return

}

vm.answer = 'Thinking...'

axios.get('https://yesno.wtf/api')

.then(function (response) {

vm.answer = _.capitalize(response.data.answer)

})

.catch(function (error) {

vm.answer = 'Error! Could not reach the API. ' + error

})

},

// 这是我们为用户停止输入等待的毫秒数

500

)

}

})

</script>


</>code

  1. /* @flow */
  2. import { queueWatcher } from './scheduler'
  3. import Dep, { pushTarget, popTarget } from './dep'
  4. import {
  5.   warn,
  6.   remove,
  7.   isObject,
  8.   parsePath,
  9.   _Set as Set,
  10.   handleError
  11. } from '../util/index'
  12. let uid = 0
  13. /**
  14.  * A watcher parses an expression, collects dependencies,
  15.  * and fires callback when the expression value changes.
  16.  * This is used for both the $watch() api and directives.
  17.    一个 watcher编译成 一个表达式 和 依赖集合, 还能出发回调当 v-model的值改变
  18.     这也能用到wathcer api中, 如果 vm.$watch('abc', fn);
  19.  */
  20. export default class Watcher {
  21.   vm: Component;
  22.   expression: string;
  23.   cb: Function;
  24.   id: number;
  25.   deep: boolean;
  26.   user: boolean;
  27.   lazy: boolean;
  28.   sync: boolean;
  29.   dirty: boolean;
  30.   active: boolean;
  31.   deps: Array<Dep>;
  32.   newDeps: Array<Dep>;
  33.   depIds: Set;
  34.   newDepIds: Set;
  35.   getter: Function;
  36.   value: any;
  37.   constructor (
  38.     vm: Component,
  39.     expOrFn: string | Function,
  40.     cb: Function,
  41.     options?: Object
  42.   ) {
  43.     //这个watcher所属的vm
  44.     this.vm = vm
  45.     // 一个vm 有多个watchers , vm.$watch(a,fn1)  vm.$watch(b,fn2) {{b.UpperCase()}} 等等
  46.     vm._watchers.push(this)
  47.     // options
  48.     if (options) {
  49.       //是否深度检测依赖
  50.       this.deep = !!options.deep
  51.       this.user = !!options.user
  52.       this.lazy = !!options.lazy
  53.       this.sync = !!options.sync
  54.     } else {
  55.       this.deep = this.user = this.lazy = this.sync = false
  56.     }
  57.     this.cb = cb
  58.     this.id = ++uid // uid for batching
  59.     this.active = true
  60.     this.dirty = this.lazy // for lazy watchers
  61.     this.deps = []
  62.     this.newDeps = []
  63.     this.depIds = new Set()
  64.     this.newDepIds = new Set()
  65.     this.expression = process.env.NODE_ENV !== 'production'
  66.       ? expOrFn.toString()
  67.       : ''
  68.     // parse expression for getter
  69.     if (typeof expOrFn === 'function') {
  70.       //监控函数
  71.       this.getter = expOrFn
  72.     } else {
  73.       //监控表达式, 注意 这里也会返回一个路径的函数
  74.       this.getter = parsePath(expOrFn)
  75.       if (!this.getter) {
  76.         this.getter = function () {}
  77.         process.env.NODE_ENV !== 'production' && warn(
  78.           `Failed watching path: "${expOrFn}" ` +
  79.           'Watcher only accepts simple dot-delimited paths. ' +
  80.           'For full control, use a function instead.',
  81.           vm
  82.         )
  83.       }
  84.     }
  85.     this.value = this.lazy
  86.       ? undefined
  87.       : this.get()
  88.   }
  89.   /**
  90.    * Evaluate the getter, and re-collect dependencies.
  91.    */
  92.   get () {
  93.     //Dep.target = this
  94.     pushTarget(this)
  95.     let value
  96.     const vm = this.vm
  97.     if (this.user) {
  98.       try {
  99.         // 因为传入了 vm, 所以在methods中可以取得this.data.abc
  100.         // 比如 this.getter 是 fucntion(){ return this.price * this.nums; }; 因为执行这个函数, 也就会去获取 this.price 和 this.nums的值
  101.         // 就会分别触发这两个数据的get方法, 然后这个watcher就会加入这两个数据的dep, this.push(depq) this.push(dep2); 通过这一步就收集了这个函数的两个依赖
  102.         value = this.getter.call(vm, vm)
  103.       } catch (e) {
  104.         handleError(e, vm, `getter for watcher "${this.expression}"`)
  105.       }
  106.     } else {
  107.       value = this.getter.call(vm, vm)
  108.     }
  109.     // "touch" every property so they are all tracked as
  110.     // dependencies for deep watching
  111.     //“触摸”每一个属性,这样它们都被跟踪为 深度观察依赖
  112.     if (this.deep) {
  113.       traverse(value)
  114.     }
  115.    
  116.     popTarget()
  117.     this.cleanupDeps()
  118.     return value
  119.   }
  120.   /**
  121.    * Add a dependency to this directive.
  122.      添加一个依赖到这个指令
  123.    */
  124.   addDep (dep: Dep) {
  125.     const id = dep.id
  126.     if (!this.newDepIds.has(id)) {
  127.       this.newDepIds.add(id)
  128.       this.newDeps.push(dep)
  129.       if (!this.depIds.has(id)) {
  130.         dep.addSub(this)
  131.       }
  132.     }
  133.   }
  134.   /**
  135.    * Clean up for dependency collection.
  136.    */
  137.   cleanupDeps () {
  138.     let i = this.deps.length
  139.     while (i--) {
  140.       const dep = this.deps[i]
  141.       if (!this.newDepIds.has(dep.id)) {
  142.         dep.removeSub(this)
  143.       }
  144.     }
  145.     let tmp = this.depIds
  146.     this.depIds = this.newDepIds
  147.     this.newDepIds = tmp
  148.     this.newDepIds.clear()
  149.     tmp = this.deps
  150.     this.deps = this.newDeps
  151.     this.newDeps = tmp
  152.     this.newDeps.length = 0
  153.   }
  154.   /**
  155.    * Subscriber interface.
  156.    * Will be called when a dependency changes.
  157.    */
  158.   update () {
  159.     /* istanbul ignore else */
  160.     if (this.lazy) {
  161.       this.dirty = true
  162.     } else if (this.sync) {
  163.       this.run()
  164.     } else {
  165.       queueWatcher(this)
  166.     }
  167.   }
  168.   /**
  169.    * Scheduler job interface.
  170.    * Will be called by the scheduler.
  171.    */
  172.   run () {
  173.     if (this.active) {
  174.       const value = this.get()
  175.       if (
  176.         value !== this.value ||
  177.         // Deep watchers and watchers on Object/Arrays should fire even
  178.         // when the value is the same, because the value may
  179.         // have mutated.
  180.         isObject(value) ||
  181.         this.deep
  182.       ) {
  183.         // set new value
  184.         const oldValue = this.value
  185.         this.value = value
  186.         if (this.user) {
  187.           try {
  188.             this.cb.call(this.vm, value, oldValue)
  189.           } catch (e) {
  190.             handleError(e, this.vm, `callback for watcher "${this.expression}"`)
  191.           }
  192.         } else {
  193.           this.cb.call(this.vm, value, oldValue)
  194.         }
  195.       }
  196.     }
  197.   }
  198.   /**
  199.    * Evaluate the value of the watcher.
  200.    * This only gets called for lazy watchers.
  201.      计算一个watcher的值, 这个只会被 延迟watchers调用
  202.    */
  203.   evaluate () {
  204.     this.value = this.get()
  205.     this.dirty = false
  206.   }
  207.   /**
  208.    * Depend on all deps collected by this watcher.
  209.      通过这个watcher, 收集所有的依赖?
  210.    */
  211.   depend () {
  212.     let i = this.deps.length
  213.     while (i--) {
  214.       this.deps[i].depend()
  215.     }
  216.   }
  217.   /**
  218.    * Remove self from all dependencies' subscriber list.
  219.      从所有的依赖订阅清单中移除自己
  220.    */
  221.   teardown () {
  222.     if (this.active) {
  223.       // remove self from vm's watcher list
  224.       // this is a somewhat expensive operation so we skip it
  225.       // if the vm is being destroyed.
  226.       // 移除依赖是一个昂贵的操作, 所有如果这个vm已经销毁le, 我们就跳一跳
  227.       if (!this.vm._isBeingDestroyed) {
  228.         remove(this.vm._watchers, this)
  229.       }
  230.       let i = this.deps.length
  231.       while (i--) {
  232.         this.deps[i].removeSub(this)
  233.       }
  234.       this.active = false
  235.     }
  236.   }
  237. }
  238. /**
  239.  * Recursively traverse an object to evoke all converted
  240.  * getters, so that every nested property inside the object
  241.  * is collected as a "deep" dependency.
  242.    递归追踪一个对象去唤起所有的已经转换的getters,
  243.    这样在一个对象的所以嵌套的熟悉都被收集成为一个深层的依赖   
  244.  */
  245. const seenObjects = new Set()
  246. function traverse (val: any) {
  247.   seenObjects.clear()
  248.   _traverse(val, seenObjects)
  249. }
  250. function _traverse (val: any, seen: Set) {
  251.   let i, keys
  252.   const isA = Array.isArray(val)
  253.   if ((!isA && !isObject(val)) || !Object.isExtensible(val)) {
  254.     return
  255.   }
  256.   if (val.__ob__) {
  257.     const depId = val.__ob__.dep.id
  258.     if (seen.has(depId)) {
  259.       return
  260.     }
  261.     seen.add(depId)
  262.   }
  263.   if (isA) {
  264.     i = val.length
  265.     while (i--) _traverse(val[i], seen)
  266.   } else {
  267.     //for in 都不用了, 加快速度
  268.     keys = Object.keys(val)
  269.     i = keys.length
  270.     while (i--) _traverse(val[keys[i]], seen)
  271.   }
  272. }


如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (1217人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号