web component 使用的是影子dom

事件

  1. const template = document.createElement('template');
  2. template.innerHTML = `
  3. <style>
  4. #box{
  5. width:200px;
  6. height:150px;
  7. border:1px solid red;
  8. display:flex;
  9. justify-content:center;
  10. align-items:center;
  11. }
  12. </style>
  13. <div id="box">
  14. <button id="click"></button>
  15. <button id="del"></button>
  16. </div>
  17. `;
  18. window.customElements.define('user-demo', class UserDemo extends HTMLElement {
  19. constructor() {
  20. super();
  21. this.attachShadow({
  22. mode: 'open'
  23. }).appendChild(
  24. template.content.cloneNode(true) // 复制节点 每个都是独立的
  25. )
  26. this.oClick = this.shadowRoot.getElementById("click");
  27. this.oDel = this.shadowRoot.getElementById("del");
  28. this.oClick.innerHTML = 'click'
  29. this.oDel.innerHTML = 'delete'
  30. }
  31. /**
  32. * connectedCallback :当 custom element首次被插入文档DOM时,被调用。
  33. * disconnectedCallback :当 custom element从文档DOM中删除时,被调用。
  34. * adoptedCallback :当 custom element被移动到新的文档时,被调用。
  35. * attributeChangedCallback :当 custom element增加、删除、修改自身属性时,被调用。
  36. */
  37. connectedCallback() {
  38. console.log('connectedCallback 文档首次被插入DOM时候被调用');
  39. this.oClick.addEventListener('click', this.btnClick)
  40. this.oDel.addEventListener('click', this.btnDel)
  41. }
  42. disconnectedCallback() {
  43. console.log('disconnectedCallback');
  44. }
  45. adoptedCallback() {
  46. console.log('adoptedCallback');
  47. }
  48. attributeChangedCallback() {
  49. console.log('attributeChangedCallback 增加,删除,需改属性时候被调用');
  50. }
  51. btnClick() {
  52. console.log('click 事件');
  53. }
  54. btnDel() {
  55. this.remove()
  56. }
  57. })

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>