Lit Framework Guide
Basic Component
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>
`;
}
}
// Use in HTML
// <my-counter label="Clicks"></my-counter>
Template Syntax
render() {
return html`
<!-- expressions -->
<p>${this.name}</p>
<!-- attribute binding -->
<input .value=${this.val} ?disabled=${this.isDisabled}>
<!-- event -->
<button @click=${this.handleClick}>Click</button>
<!-- conditional -->
${this.show ? html`<p>Visible</p>` : nothing}
<!-- loop -->
${this.items.map(i => html`<li>${i}</li>`)}
<!-- slot -->
<slot name="header"></slot>
`;
}
Lifecycle Callbacks
| Method | When |
|---|---|
| connectedCallback | Added to DOM |
| disconnectedCallback | Removed from DOM |
| firstUpdated | After first render |
| updated | After every update |
| willUpdate | Before re-render |