web通用,作用域组件

289 阅读1分钟

实现

/** 具有作用域的DOM组件 */
export class ShadowDom extends HTMLElement {
    public _shadow: ShadowRoot;
    public _fragment: DocumentFragment;
    constructor() {
        super();
        this._shadow = this.attachShadow({ mode: 'open' });
        this._fragment = document.createDocumentFragment();

        const config = { attributes: true };
        const o = new MutationObserver(this.update);
        o.observe(this, config);
    }
    update(mutationList, observer) {
        [].slice.call(this.children).forEach((child) => this._fragment.appendChild(child));
        this.shadowRoot!.appendChild(this._fragment);
    }
}

使用

// 注册组件
customElements.define('shadow-dom', ShadowDom);
<!-- 使用 -->
<shadow-dom>
    <!-- 这里写任意元素(scc, script, div, ...) -->
</shadow-dom>

生命周期

developer.mozilla.org/zh-CN/docs/…