原生组件
入口文件
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> </head> <body> <custom-button></custom-button> <script src="btn.js" type="module"></script> </body> </html>
组件
class CustomButton extends HTMLElement { constructor() { super() // open/closed const shadowRoot = this.attachShadow({ mode: 'open' }) shadowRoot.innerHTML = this.template() shadowRoot.querySelector('#btn').addEventListener("click", () => { console.log("this:", this) }) } template () { return ` <style> button { display: inline-block; line-height: 1; white-space: nowrap; cursor: pointer; text-align: center; box-sizing: border-box; outline: none; margin: 0; transition: .1s; font-weight: 500; padding: 12px 20px; font-size: 14px; border-radius: 4px; color: #fff; background-color: #409eff; border-color: #409eff; border: 0; } button:active { background: #3a8ee6; border-color: #3a8ee6; color: #fff; } </style> <button id="btn">自定义按钮</button>` } // 生命周期 // connectedCallback: 当自定义元素第一次被连接到文档 DOM 时被调用。 // disconnectedCallback: 当自定义元素与文档 DOM 断开连接时被调用。 // adoptedCallback: 当自定义元素被移动到新文档时被调用。 // attributeChangedCallback: 当自定义元素的一个属性被增加、移除或更改时被调用。 connectedCallback () { console.log('connectedCallback') } } customElements.define('custom-button', CustomButton)

浙公网安备 33010602011771号