7

我正在尝试 Octane,出于某种原因,如果我在模板中显示一个数组并向其中添加一个新对象,则 UI 不会更新。我究竟做错了什么?

这是我的模板:

<label for="new-field-name">Field Name</label>
<Input id="new-field-name" @value={{this.newFieldName}} type="text" />
<button {{on "click" this.addField}}>Add field</button>

{{#each this.fields as |field|}}
    <p>{{field.name}}</p>
{{/each}}

和组件:

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

export default class ConfigControlsComponent extends Component {
    @tracked fields = []
    @tracked newFieldName = ''

    @action addField() {
        this.fields.push({
            name: this.newFieldName
        })
        console.log(this.fields)
    }
}

显示console.log了添加了新对象的数组,并fields跟踪了数组,但是当我单击按钮时没有任何变化。

4

2 回答 2

7

当您使用tracked数组时,您需要“重置”数组,以便 Ember 注意到发生了变化。this.fields = this.fields在将新对象推入数组后 尝试做。

编辑:一些短绒将防止自我分配。因此,相反,我们可以从不变性模式中提取,并使用新数组进行设置,如下所示。

export default class ConfigControlsComponent extends Component {
  @tracked fields = []
  @tracked newFieldName = ''

  @action addField() { 
    // add this line
    this.fields = [...this.fields, {
      name: this.newFieldName
    }]; 
  }
}

如果您尝试使用tracked对象而不是数组,则有两种选择:

首先,您可以创建一个跟踪对象上所有属性的类:

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

class Address {
  @tracked street;
  @tracked city;
}

class Person {
  address = new Address();

  get fullAddress() {
    let { street, city } = this.address;

    return `${street}, ${city}`;
  }
}

或者,第二,您可以使用与上述数组示例相同的“重置”方法。

于 2019-08-12T21:13:53.983 回答
0

如果其中一个元素发生更改,则不会自动跟踪数组。你不能这样做:

this.fields.push({
        name: this.newFieldName
    })

但是,如果您更改整个数组,它们会被跟踪,例如使用扩展运算符:

this.fields = [...this.fields, {name: this.newFieldName}]

或者最终您可以使用EmberArray,请参阅https://guides.emberjs.com/release/in-depth-topics/autotracking-in-depth/#toc_arrays

于 2021-10-19T13:51:39.800 回答