web component dome

330 阅读1分钟

web component的入门dome,并无任何实际意义

html文件

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <el-button>这个是自定义的button</el-button>

    <template id="el_button">
      <button class="el-button">
        <slot>默认按钮</slot>
      </button>
    </template>
  </body>
</html>


js文件

<script>
      class ElButton extends HTMLElement {
        constructor() {
          super()
          const showDom = this.attachShadow({ mode: 'open' })
          const tpl = document.getElementById('el_button')
          const copyTpl = tpl.content.cloneNode(true)

          showDom.appendChild(copyTpl)
        }
      }

      window.customElements.define('el-button', ElButton)
</script>

展示效果

这样我们的自定义的el-button就被自动渲染到了页面上。同时web-component的页面样式是独立的,每个ShadowDom都是一个黑盒,css是独立的。