Stencil.js Guide
Component Example
import { Component, Prop, State, Event, EventEmitter, h } from '@stencil/core';
@Component({
tag: 'my-button',
styleUrl: 'my-button.css',
shadow: true, // Shadow DOM encapsulation
})
export class MyButton {
@Prop() label: string = 'Click me';
@Prop() disabled: boolean = false;
@State() clickCount: number = 0;
@Event() buttonClick: EventEmitter<number>;
handleClick() {
this.clickCount++;
this.buttonClick.emit(this.clickCount);
}
render() {
return (
<button disabled={this.disabled} onClick={() => this.handleClick()}>
{this.label} ({this.clickCount})
</button>
);
}
}
Decorators Reference
| Decorator | Purpose |
|---|---|
| @Component | Define web component tag, styles |
| @Prop | Public attribute/property |
| @State | Internal reactive state |
| @Event | Custom DOM event emitter |
| @Listen | Listen to DOM events |
| @Method | Expose public method |
| @Element | Reference to host element |
| @Watch | Watch prop/state for changes |
Quick Start
npm init stencil component my-components
cd my-components
npm install
npm start # dev server
npm run build # production build