简体   繁体   English

Vue.js如何在计算属性中设置观察者?

[英]How does Vue.js set observers in computed properties?

If I have a computed property that looks like this: 如果我有一个看起来像这样的计算属性:

computed: {
  greeting() {
    const state = this.$store.state;
    if (state.name === 'Joe') {
      return 'Hey, Joe';
    } else {
      return 'Hello, ' + state.name;
    }
  }
}

What object(s) is Vue going to set an observer on? Vue将在哪些对象上设置观察者? this.$store.state or state.name or both? this.$store.statestate.name还是两者? Asking because: 询问原因:

  • I want to make sure this Vue instance isn't listening for any and all changes to the Vuex store -- it seems like that could degrade performance in a large application. 我想确保该Vue实例不监听Vuex存储的任何和所有更改-似乎那样会降低大型应用程序的性能。
  • I have a business requirement to set some computed properties via props, and I'm having a hard time getting them to be reactive. 我有一项业务需求,要通过道具设置一些计算属性,并且很难使它们具有反应性。
  • I'm just plain curious. 我只是很好奇。

Provided that the this.$store.state and this.$store.state.name properties are reactive (they should be), then Vue will observe changes to these properties and re-evaluate greeting when the values of these properties change. 假设this.$store.statethis.$store.state.name属性是反应性的(应该是反应性的),则Vue将观察到这些属性的更改,并在这些属性的值更改时重新评估greeting

No other properties will be observed. 不会观察到其他属性。

This will cause greeting to be re-evaluated: 这将导致greeting被重新评估:

this.$store.state.name = 'foo';
this.$store.state = bar();

This will not cause greeting to be re-evaluated: 不会导致greeting被重新评估:

this.$store.state.foo = 'foo';
this.$store.state.a.b.c = 'bar';
this.$store.apple = 'pink lady';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM