Stencil.js指南

组件示例

import { Component, Prop, State, Event, EventEmitter, h } from '@stencil/core'; @Component({ tag: 'my-button', styleUrl: 'my-button.css', shadow: true, // Shadow DOM 封装 }) 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> ); } }

装饰器参考

装饰器用途
@Component定义Web组件标签和样式
@Prop公共属性
@State内部响应式状态
@Event自定义DOM事件发射器
@Listen监听DOM事件
@Method暴露公共方法
@Element宿主元素引用
@Watch监听属性/状态变化

快速入门

npm init stencil component my-components cd my-components npm install npm start # 开发服务器 npm run build # 生产构建