Lit框架指南

基础组件

import { LitElement, html, css } from 'lit'; import { customElement, property, state } from 'lit/decorators.js'; @customElement('my-counter') class MyCounter extends LitElement { static styles = css` button { background: #3b82f6; color: white; border: none; padding: 6px 12px; border-radius: 4px; } `; @property({ type: String }) label = 'Count'; @state() private count = 0; render() { return html` <div> <p>${this.label}: ${this.count}</p> <button @click=${() => this.count++}>+1</button> <button @click=${() => this.count = 0}>Reset</button> </div> `; } } // HTML 中使用 // <my-counter label="Clicks"></my-counter>

模板语法

render() { return html` <!-- 表达式 --> <p>${this.name}</p> <!-- 属性绑定 --> <input .value=${this.val} ?disabled=${this.isDisabled}> <!-- 事件 --> <button @click=${this.handleClick}>Click</button> <!-- 条件 --> ${this.show ? html`<p>Visible</p>` : nothing} <!-- 循环 --> ${this.items.map(i => html`<li>${i}</li>`)} <!-- slot --> <slot name="header"></slot> `; }

生命周期回调

方法触发时机
connectedCallback添加到DOM
disconnectedCallback从DOM移除
firstUpdated第一次渲染后
updated每次更新后
willUpdate重新渲染前