您如何呈现和过滤来自@argument 的数据集合?

How do you render and filter over a collection of data from an @argument?

这个问题来自我们的Ember Discord


我有这样的东西

{{#each @data as |project|}}
  <ItemList @categories={{project.category}}/>
{{/each}}

我在其他地方调用操作,然后过滤@data,我想重置这个each @data

我想将过滤后的结果分配给@data 从父组件传递给这个的数据

在同一个组件我有按钮

<li 
  class="inline hover:underline cursor-pointer ml-4" 
  {{on "click" (fn this.changeProject project.name @data)}}
>
  {{project.name}}
</li>

changeProject 操作过滤我想重新分配给#each 的@data 例如 - this.data = filteredModel; 不起作用。

假设您的操作,changeProject 看起来像这样:

@action
changeProject(projectName, data) {
  this.data = data.filter(project => project.name.includes(projectName));
}

this.data 不起作用的观察结果是正确且有意的,因为 @datathis.args.data 可用,但 this.args 上的每个键都是不可变的。

所以,在您的组件中,为了引用过滤后的数据,也许您想创建一个别名:

get filteredData() {
  return this.args.data;
}

并在您的模板中:

{{#each this.filteredData as |project|}}
  ...

然后您的操作也需要更新,因为我们仍然无法设置filteredData this.args.data

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

export default class Demo extends Component {
  @tracked filtered;

  get filteredData() {
    return this.filtered ?? this.args.data;
  }

  @action
  changeProject(projectName) {
    this.filtered = this.args.data.filter(project => project.name.includes(projectName));
  }
}
{{#each this.filteredData as |project|}}
  <ItemList @categories={{project.category}}/>
{{/each}}

...
<ul>
  {{#each @data as |project}}
    <li 
      class="inline hover:underline cursor-pointer ml-4" 
      {{on "click" (fn this.changeProject project.name)}}
    >
      {{project.name}}
    </li>
  {{/each}}
</ul>