直接用litelement,别手动拼lit-html+htmlelement——后者需手动处理属性同步、重渲染触发和样式注入,漏一则出bug;必须用@customelement装饰器或customelements.define()注册,否则类写完也不被识别;命名须含短横线(如my-button),否则抛domexception。

直接用 LitElement,别自己拼 lit-html + HTMLElement —— 后者要手动处理属性同步、重渲染触发、样式注入,漏一个就出 bug。
为什么必须用 @customElement 装饰器或 customElements.define()
类写完了但没注册,浏览器根本不会解析这个标签。比如写了 class MyButton extends LitElement,却忘了 customElements.define('my-button', MyButton),HTML 里放 <my-button></my-button> 就是空白,控制台也不报错,只默默失效。
- 命名必须含短横线:
my-button✅,mybutton或MyButton❌,会抛DOMException: "The element name must contain a hyphen" - 装饰器方式需确保已引入
lit/decorators.js,且 Babel 或 TypeScript 配置启用装饰器支持("experimentalDecorators": true) - Vite 构建时若用
lib模式输出,customElements.define()必须写在组件文件末尾,否则打包后可能被 tree-shaken 掉
static properties 怎么设才让 attribute 和 property 正确同步
不声明 properties,count="5" 进来就是字符串,改 this.count = 10 也不会更新 DOM 上的 count 属性;设了但类型错,比如数组硬塞进 attribute,结果得到 "[object Object]"。
-
count: { type: Number }→<my-counter count="42"></my-counter>自动转数字,且this.count = 100会反向更新 attribute(需加reflect: true) -
items: { type: Array }→ attribute 不支持传数组,<my-list items='["a","b"]'></my-list>实际是字符串,应改用 JS property:el.items = [1, 2, 3] - 没声明类型的 property(如
@property() label)默认为String,且不 reflect 到 attribute,适合内部状态,别指望它响应 HTML 属性变化
样式怎么写才能真正 scoped 且不泄漏
用 static styles = css`...`,别在 render() 里手动 appendChild(<style>...</style>) —— 前者自动注入 shadow root,后者容易重复插入、污染全局、无法复用。
-
:host匹配自定义元素自身,:host(.active)可响应外部 class 控制 - 外部传入的 class(如
<my-card class="large"></my-card>)不会自动透入 shadow DOM,得靠:host-context(.large)或显式暴露 slot - 如果用了
adoptedStyleSheets手动注入,注意 Vite 构建时 CSS 文件路径可能失效,优先走css标签函数
最容易被忽略的是:复杂对象(如 Date、Function、嵌套结构)根本不能靠 attribute 传,必须走 JS property;还有 authentik 等特定项目里,得继承 AKElement 而非 LitElement,否则生命周期或 API 行为会不一致。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











