在 Ember 1.13 及更高版本中,在遍历字符串数组时我应该使用什么键?
In Ember 1.13 and later what key should I use with each when iterating over an array of strings?
在 Ember 1.13 中,以下代码生成警告:
{{#each widgetNames as |widgetName|}}
{{component widgetName removeWidget="removeWidget"}}
{{/each}}
其中 widgetNames 是父控制器中的字符串数组。
widgetNames: []
在 Ember 1.13 中,我现在收到此警告:
WARNING: Using {{each}}
without specifying a key can lead to unusual
behavior. Please specify a key
that identifies a unique value on
each item being iterated. E.g. {{each model key="@guid" as |item|}}
.
这在您的典型模型场景中很容易修复,但我如何为字符串数组指定键?
编辑:这个问题处理了一个警告,您现在在 Ember 1.13 中迭代字符串数组时会收到警告。如果您遇到此警告,则说明您并未明确寻找像 Accessing Index in #each in emberjs. Infact, Artych's answer shows two other possible keys to use that would not be relevant or present in an answer to Accessing Index in #each in emberjs 这样的 @index 参数,因为这是特定于 @index 参数本身的。
更新(2018 年 6 月)
在 Ember 1.13.2 中,默认使用 key="@identity"
,以防止用户必须为每个 {{each}}
调用指定一个 key=
。
@guid
和 @item
已弃用,取而代之的是新的默认值。
https://github.com/emberjs/ember.js/releases/tag/v1.13.2
https://github.com/emberjs/ember.js/pull/11461
================= Ember 1.13、1.13.1 的答案 =========
您可以使用 key="@index"
或 key="@item"
。
key
( docs )有几个特殊值:
@index
- 项目在数组中的索引。
@item
- 数组本身中的项目。这只能用于字符串数组
或数字。
@guid
- 为每个对象生成唯一标识符(使用 Ember.guidFor
)。
{{#each widgetNames key="@index" as |widgetName|}}
{{component widgetName removeWidget="removeWidget"}}
{{/each}}
在 Ember 1.13 中,以下代码生成警告:
{{#each widgetNames as |widgetName|}}
{{component widgetName removeWidget="removeWidget"}}
{{/each}}
其中 widgetNames 是父控制器中的字符串数组。
widgetNames: []
在 Ember 1.13 中,我现在收到此警告:
WARNING: Using
{{each}}
without specifying a key can lead to unusual behavior. Please specify akey
that identifies a unique value on each item being iterated. E.g.{{each model key="@guid" as |item|}}
.
这在您的典型模型场景中很容易修复,但我如何为字符串数组指定键?
编辑:这个问题处理了一个警告,您现在在 Ember 1.13 中迭代字符串数组时会收到警告。如果您遇到此警告,则说明您并未明确寻找像 Accessing Index in #each in emberjs. Infact, Artych's answer shows two other possible keys to use that would not be relevant or present in an answer to Accessing Index in #each in emberjs 这样的 @index 参数,因为这是特定于 @index 参数本身的。
更新(2018 年 6 月)
在 Ember 1.13.2 中,默认使用 key="@identity"
,以防止用户必须为每个 {{each}}
调用指定一个 key=
。
@guid
和 @item
已弃用,取而代之的是新的默认值。
https://github.com/emberjs/ember.js/releases/tag/v1.13.2 https://github.com/emberjs/ember.js/pull/11461
================= Ember 1.13、1.13.1 的答案 =========
您可以使用 key="@index"
或 key="@item"
。
key
( docs )有几个特殊值:
@index
- 项目在数组中的索引。@item
- 数组本身中的项目。这只能用于字符串数组 或数字。@guid
- 为每个对象生成唯一标识符(使用Ember.guidFor
)。{{#each widgetNames key="@index" as |widgetName|}} {{component widgetName removeWidget="removeWidget"}} {{/each}}