條件式
由於 Lit 利用了普通的 Javascript 表達式,您可以使用標準的 Javascript 控制流程結構,例如條件運算子、函式呼叫以及if
或switch
陳述式來渲染條件內容。
JavaScript 條件式還允許您組合巢狀樣板表達式,您甚至可以將樣板結果儲存在變數中以供其他地方使用。
使用條件(三元)運算子的條件式
“使用條件(三元)運算子的條件式”的永久連結使用條件運算子?
的三元表達式是新增內聯條件式的絕佳方式
render() {
return this.userName
? html`Welcome ${this.userName}`
: html`Please log in <button>Login</button>`;
}
使用 if 陳述式的條件式
“使用 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 指令
“快取樣板結果:cache 指令”的永久連結在大多數情況下,JavaScript 條件式是您處理條件樣板所需的一切。但是,如果您要在大型複雜的樣板之間切換,您可能需要節省每次切換時重新建立 DOM 的成本。
在這種情況下,您可以使用cache
指令。cache 指令會快取目前未渲染的樣板的 DOM。
render() {
return html`${cache(this.userName ?
html`Welcome ${this.userName}`:
html`Please log in <button>Login</button>`)
}`;
}
有關詳細資訊,請參閱cache 指令。
有條件地渲染空白
“有條件地渲染空白”的永久連結有時,您可能需要在條件運算子的一個分支中不渲染任何內容。這通常是子表達式所需要的,有時在屬性表達式中也需要。
對於子表達式,值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>`