4

我试图将我所有的 ember 组件转换为 OCTANE 版本。但我有一个更大的疑问。如何将observer代码转换为 OCTANE 版本?例如,

parent.hbs
 
 <Child @value={{this.value}} />

child.hbs

 <div>{{this.newUpdate}}</div>

child.js

  export default class ChildComponent extends Component {     
      /** Previous code: sample code only
        valueUpdate: observer('value', function() {
            this.newValue = this.value / 12 * 2;
        })
      */
  }

如何将观察者更新为辛烷值?有什么想法请...

注意:我尝试使用“@observer”,但它在组件内不起作用。

4

1 回答 1

2

Ember Octane follows another programming model in that regard. Instead of observing a property and updating another one whenever it changes, you should use a native getter to derive state.

import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';

export default class ChildComponent extends Component {
  // I assume that value is a local state of this component.
  // If it's an argument passed to the component on invocation.
  // You don't need to declare it here but can reference
  // this.args.value directly in the getter.
  @tracked value;

  get newValue() {
    return this.value / 12 * 2;
  }
}

只要该值是从跟踪的属性派生的,模板就会在其更改时重新呈现。无需像使用计算属性那样使用观察者手动更新值或显式列出依赖项。

传递给组件的参数是自动跟踪的。因此,如果value不是本地状态而是作为参数传入,它就像这样简单:

import Component from '@glimmer/component';

export default class ChildComponent extends Component {
  get newValue() {
    return this.args.value / 12 * 2;
  }
}
于 2020-12-28T14:19:30.530 回答