条件渲染
由于 Lit 利用的是普通的 JavaScript 表达式,你可以使用标准的 JavaScript 控制流结构来渲染条件内容,例如条件运算符、函数调用以及 if 或 switch 语句。
JavaScript 条件语句还允许你组合嵌套的模板表达式,你甚至可以将模板结果存储在变量中以供其他地方使用。
使用条件(三元)运算符进行条件渲染
Permalink to "使用条件(三元)运算符进行条件渲染"使用条件运算符 ? 的三元表达式是添加内联条件渲染的好方法:
render() { return this.userName ? html`Welcome ${this.userName}` : html`Please log in <button>Login</button>`;} 使用 if 语句进行条件渲染
Permalink to "使用 if 语句进行条件渲染"你可以在模板外部使用 if 语句来表达条件逻辑,计算出要在模板内部使用的值:
render() { let message; if (this.userName) { message = html`Welcome ${this.userName}`; } else { message = html`Please log in <button>Login</button>`; } return html`<p class="message">${message}</p>`;} 或者,你也可以将逻辑提取到一个单独的函数中,以简化模板:
getUserMessage() { if (this.userName) { return html`Welcome ${this.userName}`; } else { return html`Please log in <button>Login</button>`; }}render() { return html`<p>${this.getUserMessage()}</p>`;} 缓存模板结果:cache 指令
Permalink to "缓存模板结果:cache 指令"在大多数情况下,JavaScript 条件语句足以满足条件模板的需求。但是,如果你需要在大型、复杂的模板之间切换,你可能希望节省每次切换时重新创建 DOM 的开销。
在这种情况下,你可以使用 cache 指令。cache 指令会缓存当前未被渲染的模板的 DOM。
render() { return html`${cache(this.userName ? html`Welcome ${this.userName}`: html`Please log in <button>Login</button>`) }`;} 更多信息请参阅 cache 指令。
条件渲染为空
Permalink to "条件渲染为空"有时,你可能希望在条件运算符的某个分支中不渲染任何内容。这在子表达式中通常需要,有时在属性表达式中也需要。
对于子表达式,undefined、null、空字符串('')以及 Lit 的 nothing 哨兵值都不会渲染任何节点。更多信息请参阅移除子内容。
以下示例在值存在时渲染该值,否则不渲染任何内容:
render() { return html`<user-name>${this.userName ?? nothing}</user-name>`;} 对于属性表达式,Lit 的 nothing 哨兵值会移除该属性。更多信息请参阅移除属性。
以下示例条件渲染 aria-label 属性:
html`<button aria-label="${this.ariaLabel || nothing}"></button>`