VueJs,计算属性和观察者之间的区别? [英] VueJs, difference between computed property and watcher?

查看:35
本文介绍了VueJs,计算属性和观察者之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Vue.js 文档中有一个如下示例:

On Vue.js documentation there is an example like below:

var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar',
    fullName: 'Foo Bar'
  },
  watch: {
    firstName: function (val) {
      this.fullName = val + ' ' + this.lastName
    },
    lastName: function (val) {
      this.fullName = this.firstName + ' ' + val
    }
  }
})

上面的代码是命令式和重复的.将其与计算属性版本进行比较:

The above code is imperative and repetitive. Compare it with a computed property version:

var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
    fullName: function () {
      return this.firstName + ' ' + this.lastName
    }
  }
})

观察者比计算属性更适合的情况是什么?我应该如何决定选择哪个?文档一直说它更通用",但并没有真正实现它的目的.

What are the situations when watchers more suitable than computed properties? How should i decide which to choose? Documentation keeps saying it is more "generic" but does not really put its purpose.

推荐答案

计算属性

计算属性示例:

computed: {
   val () {
     return this.someDataProperty * someOtherVariable
   }
}

这段特定的代码有什么作用?

what does this particular piece of code do?

  1. 它为组件 创建一个名为 val 的属性(在原型上,所以 .hasOwnProperty('val') 将显示false).

  1. It creates a property named val for the component (on the prototype so <vueInstanece>.hasOwnProperty('val') would show false).

它有一个依赖树,它由 reactive 属性(数据属性、其他计算属性)组成,在这种情况下:this.someDataProperty,这意味着时刻依赖项发生变化,计算属性将被重新计算.

It has a dependency tree which consists of reactive properties (data properties, other computed properties) in this case : this.someDataProperty, which means the moment the dependencies change, the computed property will be recalculated.

虽然有争议,但不能将参数传递给它.所以像

Although debated, can't have arguments passed to it. So something like

computed: {
  val (flag) {
    return (flag === 1) 
      ? this.someDataProperty * someOtherVariable 
      : this.someDataProperty * 5
    }
}

做不到

请参阅:https://vuejs.org/v2/guide/computed.html#Computed-Setter

观察者示例:

watch: {
   val (n, o) {
     console.log(n, o)
   }
}

  1. 它不会创建任何新属性,但会监视响应式属性的变化.

  1. It does not create any new property, but it watches the changes over a reactive property.

只观察一个特定的属性,与任何依赖属性更改都可能导致重新计算的计算不同.

Watches only one specific property, unlike computed where any dependent property change can cause recalculation.

具有新旧值的参数.

<小时>

所以计算属性将是要走的路,如果:

您想要一个始终依赖于其他属性的属性.就像模板的文本格式一样,甚至是代码中的示例.

You want a property that depends on other properties always. Like text formatting for a template, which is even the example in your code.

或者减少可变长度,因为这很常见:

Or reducing variable lengths as this is quite common:

this.$store.state.someProperty.someNestedProperty.someDeeplyNestedProperty

可以简化为:

computed: {
  someDeeplyNestedProperty () {
     return this.$store.state.someProperty.someNestedProperty.someDeeplyNestedProperty
  }
}

不仅仅是减少变量大小,每次 store 更新时,您都会在 someDeeplyNestedProperty 中获得最新值.

Not just reduction in variable size, each time the store updates, you will have the latest value in the someDeeplyNestedProperty.

如果您想查看一个反应性属性是否已更改为有利值以了解您已准备好执行操作,那么 观察者 会很有用.

And Watchers are useful if you want to see if one reactive property has changed to a favourable value to know that you're ready to perform an action.

喜欢:

watch: {
  somethingSelected() {
    this.router.push('someOtherRoute')
  }
}

编辑:我看到了一些 Flavio 的好文章Copes 列出了每个用例的常见用例(方法、计算道具、观察者):

EDIT: I came across some good article by Flavio Copes who listed common use cases for each of them (methods, computed props, watchers):

何时使用方法

  • 对 DOM 中发生的某些事件做出反应

    • To react on some event happening in the DOM

      当你的组件发生某些事情时调用一个函数.您可以从计算属性或观察者调用方法.

      To call a function when something happens in your component. You can call a methods from computed properties or watchers.

      何时使用计算属性

      • 您需要从现有数据源组合新数据
      • 您在模板中使用了一个由一个或多个数据属性构建的变量
      • 您希望将复杂的嵌套属性名称简化为更易读且易于使用的名称,但要在原始属性更改时更新它
      • 您需要从模板中引用一个值.在这种情况下,最好创建一个计算属性,因为它是缓存的.
      • 您需要监听多个数据属性的变化
      • 何时使用观察者

        • 您想在数据属性更改时进行侦听,并执行某些操作
        • 你想听一个道具值的变化
        • 您只需要监听一个特定的属性(您不能同时观看多个属性)
        • 你想观察一个数据属性,直到它达到某个特定的值,然后做一些事情
        • 这篇关于VueJs,计算属性和观察者之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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