webComponent 学习笔记

472 阅读2分钟

参考博客

技术核心

  1. 自定义元素 Custom elements
  2. 影子DOM Shadow DOM
  3. HTML模板 HTML templates ps:百度前端学院还提到一个HTML导入,但存在争议,我也木有学。

影子节点的说明 image.png

自定义组件需要哪几步

1. 自定义一个模板

<template id="modal_tpl">
    <header>这里是modal</header>
    <ul>
        <li>哈喽</li>
        <li>你好</li>
        <li>请看</li>
        <li>这里</li>
    </ul>
    <button>巨星请点这里</button>
    <footer>这里是脚脚</footer>
    <style>
        header {
            padding: 10px 20px;
            border-bottom: 1px solid #f0f0f0;
            font-weight: bold;
            background: #f0f0f0;
        }
        footer {
            margin-top: 20px;
            border-top: 1px solid #f0f0f0;
            padding: 10px 20px;
            text-align: right;
        }
    </style>
</template>

2. 自定义一个类

其中有四个类似于生命周期的回调函数,具体可以参考我参考的博客链接

class Modal extends HTMLElement{
    constructor(){
        super();
        //获取模板内容
        let template=document.getElementById('modal_tpl');
        let templateContent=template.content;
        //创建shaDowRoot节点
        const shadowRoot=this.attachShadow({mode:'open'});
        //把模板的节点拷贝过去
        shadowRoot.appendChild(templateContent.cloneNode(true));
    }
    //当 custom element首次被插入文档DOM时,被调用
    connectedCallback(el){
        console.log('insert dom',el);
    }
    //当 custom element从文档DOM中删除时,被调用
    disconnctedCallback(){
        console.log('Custom square element removed from page.');
    }
    //当 custom element被移动到新的文档时,被调用
    adoptedCallback(){
    console.log('Custom square element moved to new page.');
    }
    //当 custom element增加、删除、修改自身属性时,被调用
    //要监听才能用 observedAttributes()
    attributeChangedCallback(name, oldValue, newValue) {
      
    }
    // 如果需要在元素属性变化后,触发 attributeChangedCallback()回调函数,
    // 你必须监听这个属性。这可以通过定义observedAttributes() get函数来实现
    static get observedAttributes() {
      return ['visible']; 
    }
}

3.注册自定义元素

//前者是自定义的标签名,后者是自定义类
customElements.define('xu-model',Modal);

4.尽情使用它

记得在页面末尾引用你写的js文件。

假如本页面<script>写当我没说

<xu-model>你好</xu-model>