显示有误

博客园 首页 新随笔 联系 订阅 管理

一.什么是web components?

    web components是一套允许开发人员自定义元素创建可重用组件的技术

二.怎么使用?

  1.创建一个类或函数来指定web组件功能,例如使用es6的class

  2. 通过customElements.define()方法注册自定义元素,并向其传递要定义的元素名称,指定元素功能的类,以及可选的其所继承自的元素。

  3.如果需要的话可以使用Element.attachShadow()方法将一个shadow DOM附加到自定义元素上。使用原生的DOM方法向shadow DOM中添加子元素。

 4.如果需要的话,使用<template>和<slot>定义一个HTML模板。再次使用常规DOM方法克隆模板并将其附加到shadow DOM中。

 5.最后在页面中像使用原生的HTML元素一样,使用自定义的元素

三.实例

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Web Components</title>
</head>
<body>
    <custom-button></custom-button>
      //这是自定义的元素(像使用原生HTML元素一样使用自定义的元素)
    <template id="custom-button">//使用template定义一个HTML模板
        <button>自定义按钮</button>
          //添加样式
         <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>
    </template>
    <script>
        class CustomButton extends HTMLElement {
              constructor() {
                 super()
                 const templateContent=document.getElementById('custom-button').content
            //获取自定义模板
                  const shadowRoot = this.attachShadow({mode:'open'})
                  shadowRoot.appendChild(templateContetn.cloneNode(true))
                  //使用attachShadow()方法将一个shadow DOM附加到自定义元素
                  shadowRoot.querySelector('button').onClick=()=>{
                   alert('hello world')
                 }
                 //绑定点击事件
              }
         }
       customElements.define('custom-button', CustomButton)
      //注册自定义元素
     </script>
</body>            

四.运行结果

posted on 2021-02-04 15:16  显示有误  阅读(408)  评论(0编辑  收藏  举报