Web组件继承为新的自定义元素组件实例页面

回到相关文章 »

效果:

我显示啦~

代码:

HTML代码:
<button id="button">显示loading</button>
<button id="button2">隐藏loading</button>

<p><button id="button3">显示toast</button></p>
<zxx-toast id="toast">我显示啦~</zxx-toast>

<script type="module">
import loading from './zxx-loading.js';

button.onclick = function () {
    loading.show();
};
button2.onclick = function () {
    loading.hide();
};

button3.onclick = function () {
    toast.show();
};
</script>
                
zxx-toast.js代码:
// 定义 <zxx-toast> 元素
class ZxxToast extends HTMLElement {
    static get observedAttributes () {
        return ['open'];
    }
    constructor () {
        super();
    }
    get open () {
        return this.hasAttribute('open');
    }

    set open (val) {
        this.toggleAttribute('open', val);
    }
    
    render () {
        setTimeout(() => {
            this.hide();
        }, 3000);
    }
    
    show () {
        this.open = true;
    }

    hide () {
        this.open = false;    
    }
    
    attributeChangedCallback (name, oldval, newval) {
        if (name == 'open' && this.open) {
            this.render();
        }
    }
}

if (!customElements.get('zxx-toast')) {
    customElements.define('zxx-toast', ZxxToast);
}

export default ZxxToast;
                
zxx-loading.js代码:
// 定义 <zxx-loading> 元素
import ZxxToast from './zxx-toast.js';
class ZxxLoading extends ZxxToast {
    render () {
        // 显示 loading 内容
        this.innerHTML = '<i class="spin"></i>';
    }
}

if (!customElements.get('zxx-loading')) {
    customElements.define('zxx-loading', ZxxLoading);
}

export default ZxxLoading;

// 增加两个静态方法
ZxxLoading.show = function () {
    if (!this.loading) {
        this.loading = new ZxxLoading();
        document.body.append(this.loading);
    }
    
    this.loading.open = true;
    
    return this.loading;
};
ZxxLoading.hide = function () {
    if (this.loading) {
        this.loading.open = false;    
    }    
    return this.loading;
};