调试watcher的渲染顺序

Vue

# html模板

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Vue.js 01 component example</title>
  </head>
  <body>
    <div id="app">
      {{ reversedMessage }}
      <hr>
      {{ user.fullName }}
    </div>

    <script src="../../dist/vue.js"></script>
    <script>
      const vm = new Vue({
        el: '#app',
        data: {
          message:'Hello Vue',
          user: {
            firstName: '张',
            lastName: '三',
            fullName: ''
          }
        },
        computed: {
          reversedMessage: function () {
            return this.message.split('').reverse().join('')
          }
        },
        watch: {
          // 这里不给user.firstName和lastName单独设置watcher,是因为没有办法配置立即执行immediate和深度监听deep
          // 监听对象user,要提供handler,就是回调函数,还有配置立即执行immediate和深度监听deep
          // 在侦听器里面,当数据变化的时候,还可以做异步处理这些更复杂的内容
          'user': {
            handler: function (newValue, oldValue) {
              this.user.fullName = this.user.firstName + this.user.lastName
            },
            deep: true,
            immediate: true
          }
        }
      })
    </script>
  </body>
</html>

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

# 设置断点

在 core/observer/watcher.js 中 设置断点

image

# 开始调试

F5刷新进入构造函数,看到调用栈可以看到Watcher是在哪个函数中被调用的

image

首先创建的第一个watcher就是计算属性的watcher,按F10向下执行,可以看到分配的id是1

image

下面按F8向下执行,此时的watcher是谁调用的呢?还是看调用栈

image

下面看到执行的时候其id是2

image

按F8跳到最后一个watcher中,看到其调用栈

image

可以看到它的id是3

image

我们这个时候就应该知道watcher的渲染顺序,在watcher执行的时候,会调用flusher函数,里面会对id进行从小到大排序,依次执行watcher,所以执行的时候也是按照计算,侦听和渲染的watcher顺序执行的.

更新时间: 2022-01-11 10:46