Vue 是否像计算属性一样缓存属性? [英] Do Vue watched properties cache just like the computed properties?

查看:27
本文介绍了Vue 是否像计算属性一样缓存属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Vue 文档中 提到了计算属性被巧妙地缓存,而不是使用常规方法:

In the Vue docs it is mentioned that computed properties are smartly cached as opposed to using regular methods:

相比之下,只要发生重新渲染,方法调用将始终运行该函数.为什么我们需要缓存?想象一下我们有一个昂贵的计算属性......

In comparison, a method invocation will always run the function whenever a re-render happens. Why do we need caching? Imagine we have an expensive computed property...

我的问题是:做 监视属性也有像计算属性一样的缓存?(包括 Vuex 观看,例如使用 vm.$store.watch...)

My question is: Do watched properties also having caching like computed properties? (including Vuex watching, eg. using vm.$store.watch...)

推荐答案

watchers 的行为将与 computed 的行为与 computed 的行为相同使用 watchers 在内部实现.当定义一个 computed 属性时,vue 内部会在计算属性中使用的变量上设置观察者,请参阅以下来自 来源:

Behaviour of watchers will be same as behaviour of computed as computed is internally implemented using watchers. When one defines a computed property, vue internally sets watcher on the variables used in computed property, see the code below from source:

function makeComputedGetter (getter: Function, owner: Component): Function {
  const watcher = new Watcher(owner, getter, noop, {
    lazy: true
  })
  return function computedGetter () {
    if (watcher.dirty) {
      watcher.evaluate()
    }
    if (Dep.target) {
      watcher.depend()
    }
    return watcher.value
  }
}

因此,当响应数据发生变化时,编写在 computedwatch 块中的代码只会执行一次.

So code written in computed or watch blocks will be executed only once, when the reactive data changes.

这篇关于Vue 是否像计算属性一样缓存属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆