我认为在组件上保持状态是最简单的,以防您的原始数据是硬编码的并且您不需要从服务器获取它或将其保存到服务器。
我建议查看 Octane 教程以更深入地学习这些模式。您可以在此处访问它。
在 Octane 组件中存储数组状态:
首先,我们将数组数据放入一个跟踪属性中,并编写一个可以修改该数据的操作:
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
export default class MyComponent extends Component {
@tracked items = [
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
];
@action
editItem(item) {
this.items[0][0] = item // make some changes
// The line below is important when working with tracked arrays and objects. Always "reset" the array whenever you make changes. This tells Ember to update what is rendered.
this.items = this.items;
}
}
each
我们使用助手迭代该二维数组。我们将这些项目称为this.items
因为它们是在“此组件”上定义的
<table class="quantize" style="width: 80%">
{{#each this.items as |row|}}
<tr class="">
{{#each row as |cell|}}
<td
class="border border-dark"
style="width:10%">
{{cell}}
</td>
{{/each}}
</tr>
{{/each}}
</table>
在路由模型中保持状态
如果您想将数组数据放入路由的模型挂钩中,您也可以这样做。但是,模型主要用于从 API 获取数据时。优点是 Ember 会为您处理一些异步获取和渲染,缺点是它更复杂。Octane 组件只允许更改它“拥有”的数据。如果需要对从父组件或路由传入的数据进行更改,则必须通过调用也传入的函数来完成。这称为“单向绑定”。
首先我们从路由的模型钩子返回数据:
// routes/my-route.js
import Route from '@ember/routing/route';
export default class MyRoute extends Route {
model() {
return [
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
];
// or return a fetch() request for that data
}
}
// controllers/my-route.js
import Controller from '@ember/controller';
import { action } from '@ember/object';
export default class MyRouteController extends Controller {
@action
editItems(items) {
this.model = items;
}
}
我们将该模型数据和我们的 editItems 操作传递给显示表格的组件:
<!-- templates/my-route.hbs -->
<MyComponent @items={{this.model}} @editItems={{action "editItems"}} />
在我们的组件中,我们将项目称为@items
而不是this.items
。@
当数据来自外部时使用,例如父路由或组件。
<!-- my-component.hbs -->
<table class="quantize" style="width: 80%">
{{#each @items as |row|}}
<tr class="">
{{#each row as |cell|}}
<td
class="border border-dark"
style="width:10%">
{{cell}}
</td>
{{/each}}
</tr>
{{/each}}
</table>
然后,当您想对数组进行更改时,您必须调用editItems
传入的函数。它可以作为this.args.editItems
. this.args
是从父级传递到组件的任何内容。
import Component from '@glimmer/component';
import { action } from '@ember/object';
export default class MyComponent extends Component {
@action
buttonWasClicked(item) {
this.args.editItems(item)
}
}
或者,您可以使用直接在模板中传入的操作,并将您想要更改的项目交给它。
<!-- my-component.hbs -->
<button {{on "click" (fn @editItems item)}}>edit item</button>