vue template内插值是method的遐想

85 阅读1分钟
 <template>
  <div class="hello">
    <h2>{{test()}}</h2>
  </div>
</template>

<script>
export default {
  data () {
    return {
      num: 12345
    }
  },
  mounted () {
    setInterval(() => {
      this.num = this.num + 1
    }, 2000)
  },
  methods: {
    test () {
      return this.num
    }
  }
}
</script>

通过查看上述代码可以发现,在template内的h2标签的插值是调用了一个方法,方法返回data内定义的num,mounted生命周期内开启一个interval每隔2s修改this.num的值,然后test方法也会2s被调用一次

按照以前的理解是,模版内调用的方法只会在初始化的时候触发一次,为什么这里会触发多次呢?

依赖收集机制

在初始化的时候,会调用update方法把template转换成vnode模版编译,在转换过程中会调用test方法,test方法会触发this.num的getter方法,在getter方法内进行依赖手机,会把触发模版更新的方法push到this.num的watchers数组内

触发机制

在interval内每隔2s触发this.num的set方法,接着调用ob.notify(),触发该值对应的watcher数组内的所有依赖该字段的方法

总结

其实上述代码本质上就相当于在标签内直接获取this.num, 如下

<template>
  <div class="hello">
    <h2>{{num}}</h2>
  </div>
</template>