自定义元素仅支持独立型和内置扩展型两种合法类型,独立型须继承htmlelement且类名含连字符,内置扩展型需指定extends并继承对应html接口,属性监听需声明observedattributes,注册不可撤销。

自定义元素只有两种合法类型:独立型(Autonomous)和内置扩展型(Customized built-in element),选错类型会导致注册失败或行为异常,比如 is 属性被忽略、生命周期不触发、甚至控制台静默失效。
独立自定义元素必须继承 HTMLElement
这是最常用也最容易出错的类型。类必须直接继承 HTMLElement,不能省略 super(),也不能继承 Object 或其他非 DOM 基类。
-
customElements.define('my-card', MyCard)中的MyCard必须是class MyCard extends HTMLElement - 写成
class MyCard {}会报Illegal constructor,且connectedCallback永远不会执行 - 构造函数里只能做最小初始化(如
super()、绑定this、创建 shadow root),不能读取this.innerHTML或操作子节点——那些得挪到connectedCallback里 - 标签名必须含连字符,
mycard和MyCard都非法,浏览器直接抛DOMException: The name "mycard" is not a valid custom element name
内置扩展型必须指定 { extends: 'xxx' } 并继承对应接口
想复用 <button></button> 或 <p></p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill2900" title="Markdown to HTML"><img
src="https://img.php.cn/upload/skill/000/000/081/178938727468962.jpg" alt="Markdown to HTML" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill2900" title="Markdown to HTML" class="overflowclass">Markdown to HTML</a>
<p class="overflowclass">{"answer":"将 Markdown 转换为内嵌 CSS、样式精美的独立 HTML。完美适用于新闻简报、文档、报告及邮件模板。"}</p>
</div>
<a rel="nofollow" href="/xiazai/skill2900" title="Markdown to HTML" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div> 的原生行为?必须走这条路,但写法比独立型更严格。
- 类要继承具体接口,比如扩展段落就得写
class MyParagraph extends HTMLParagraphElement,不是HTMLElement -
customElements.define('my-paragraph', MyParagraph, { extends: 'p' })—— 第三个参数对象不能漏,且extends值必须是小写字符串,'P'或'div'(无效)都不行 - HTML 中必须用
<p is="my-paragraph"></p>,直接写<my-paragraph></my-paragraph>不生效,也不会触发任何生命周期回调 - 如果继承了
HTMLButtonElement却没在define里传{ extends: 'button' },注册会成功但元素不会升级,点击事件等原生行为丢失
attributeChangedCallback 不处理初始属性值
哪怕你在 HTML 里写了 <my-input value="hello"></my-input>,attributeChangedCallback 也不会被调用——它只响应后续的 JS 修改或 setAttribute。
- 初始属性同步必须手动做:在
connectedCallback里遍历this.attributes,或在构造函数里调用this.getAttribute('value') - 要监听哪些属性,必须提前声明静态字段
static observedAttributes = ['value', 'disabled'],漏写就收不到变更通知 - 注意大小写:HTML 属性名始终小写,
observedAttributes里写'Value'或'VALUE'都无效
真正容易被忽略的是:自定义元素一旦注册,就不可撤销;重复 define 报错,但静默覆盖已有定义的行为并不存在。生产环境务必加 if (!customElements.get('my-button')) 守卫,否则热更新或多次加载脚本时会崩。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










