前面步骤中使用的方法在处理单个可迭代对象作为数据源时非常有用,但有时情况可能需要更命令式的方式。

在这个示例中,组件有以下状态属性:

为每个成员渲染一个列表项,同时在 includePetstrue 时也包含宠物。宠物的列表项应同时包含名称和种类。

根据布尔状态有条件地填充 listItems 数组,如下所示。

// my-element.ts
render() {
const listItems: TemplateResult[] = [];
this.friends.forEach((friend) => {
listItems.push(html`<li>${friend}</li>`);
});
if (this.includePets) {
this.pets.forEach((pet) => {
listItems.push(html`<li>${pet.name} (${pet.species})</li>`);
});
}
}
// my-element.js
render() {
const listItems = [];
this.friends.forEach((friend) => {
listItems.push(html`<li>${friend}</li>`);
});
if (this.includePets) {
this.pets.forEach((pet) => {
listItems.push(html`<li>${pet.name} (${pet.species})</li>`);
});
}
}

然后将 listItems 数组添加到元素的模板中。

// my-element.ts
render() {
return html`
<ul>
${listItems}
</ul>
`;
}
// my-element.js
render() {
return html`
<ul>
${listItems}
</ul>
`;
}

点击按钮查看条件渲染是否正常工作。

额外练习:尝试重构代码,将逻辑从 render() 方法中提取到一个单独的私有方法中,该方法返回模板数组。然后在模板表达式中调用新方法(替换 listItems)。