[英]Ember Octane - Display contents of a Tracked Array from Controller in Template?
[英]Why won't my tracked array update in Ember Octane?
我正在試用 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
數組,但是當我單擊按鈕時沒有任何變化。
當您對數組使用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}`;
}
}
或者,其次,您可以使用與上面的數組示例相同的“重置”方法。
如果數組元素之一發生更改,則不會自動跟蹤數組。 你不能這樣做:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.