ES6 自定义组件 webComponent

webComponent

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<!-- <myComponent>自定义组件</myComponent> -->
<!-- <ul>系统组件</ul><li>系统组件</li><span>系统组件</span> -->

<!-- <img is="my-img" /> -->
<my-component></my-component>
</body>
<script>
/* 
    1.自定义组件
    2.继承系统组件
*/
{
    // 自定义组件
    class MyComponent extends HTMLElement{
        constructor(){
            super();
            console.log(this);
            this.innerHTML = `自定义组件里的内容`;
        }
    }
    customElements.define("my-component",MyComponent);
    // 使用
    // <my-component></my-component>
}
{
    // 继承系统(HTML)组件 -> img组件
    // class MyImg extends HTMLImageElement{
    //     constructor(){
    //         super();
    //         // console.log(this);
    //         // 当我们测试成功了之后,我们可以对系统标签进行重写:
    //         setTimeout(()=>{
    //             this.src = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582927531076&di=8a52a0847b826b9c479d3224bd2140bb&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F2020-01-14%2F5e1d8d98b0595.jpg";
    //         },2000);
    //     }
    // }
    // customElements.define("my-img",MyImg,{
    //     extends:"img"
    // });//自定组件名称; -> 参数(标签组件名称,类名称,{extens:系统标签名称});
    // 使用:
    // <img is="标签组件名称" />

    class MyImg extends HTMLImageElement{
        constructor(){
            super();
            // console.log(this);
            setTimeout(()=>{
                this.src = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582927531076&di=8a52a0847b826b9c479d3224bd2140bb&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F2020-01-14%2F5e1d8d98b0595.jpg";
            },2000);
        }
    }
    customElements.define("my-img",MyImg,{
        extends:"img"
    });

}
</script>
</html>

猜你喜欢

转载自www.cnblogs.com/Afanadmin/p/12381393.html