条件渲染
由于 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>`