web component 使用的是影子dom
事件
const template = document.createElement('template');template.innerHTML = ` <style> #box{ width:200px; height:150px; border:1px solid red; display:flex; justify-content:center; align-items:center; } </style> <div id="box"> <button id="click"></button> <button id="del"></button> </div>`;window.customElements.define('user-demo', class UserDemo extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }).appendChild( template.content.cloneNode(true) // 复制节点 每个都是独立的 ) this.oClick = this.shadowRoot.getElementById("click"); this.oDel = this.shadowRoot.getElementById("del"); this.oClick.innerHTML = 'click' this.oDel.innerHTML = 'delete' } /** * connectedCallback :当 custom element首次被插入文档DOM时,被调用。 * disconnectedCallback :当 custom element从文档DOM中删除时,被调用。 * adoptedCallback :当 custom element被移动到新的文档时,被调用。 * attributeChangedCallback :当 custom element增加、删除、修改自身属性时,被调用。 */ connectedCallback() { console.log('connectedCallback 文档首次被插入DOM时候被调用'); this.oClick.addEventListener('click', this.btnClick) this.oDel.addEventListener('click', this.btnDel) } disconnectedCallback() { console.log('disconnectedCallback'); } adoptedCallback() { console.log('adoptedCallback'); } attributeChangedCallback() { console.log('attributeChangedCallback 增加,删除,需改属性时候被调用'); } btnClick() { console.log('click 事件'); } btnDel() { this.remove() }})
slot
const template = document.createElement('template');
template.innerHTML = `
<style>
#box{
width:200px;
height:150px;
border:1px solid red;
display:flex;
justify-content:center;
align-items:center;
}
</style>
<div id="box">
<h2>slot</h2>
<slot></slot>
</div>
`;
window.customElements.define('user-demo', class UserDemo extends HTMLElement {
constructor() {
super();
this.attachShadow({
mode: 'open'
}).appendChild(
template.content.cloneNode(true) // 复制节点 每个都是独立的
)
}
})
<user-demo>
<div>123</div>
</user-demo>
动态参数
const template = document.createElement('template');
template.innerHTML = `
<div id="box">
<h2 id="h2">slot</h2>
</div>
`;
window.customElements.define('user-demo', class UserDemo extends HTMLElement {
constructor() {
super();
this.attachShadow({
mode: 'open'
}).appendChild(
template.content.cloneNode(true) // 复制节点 每个都是独立的
)
this.shadowRoot.getElementById('h2').innerHTML =
this.getAttribute('h2') // user-demo 传入的参数
}
})
<user-demo h2="动态"></user-demo>
<user-demo h2="传参"></user-demo>