web components(组件)整理

各种网站往往需要一些相同的模块,比如日历、调色板等等,这种模块就被称为“组件”(component)。Web Component就是网页组件式开发的技术规范。 

1、首先创建一个js文件,命名以hello-world.js为例:

class HelloWorld extends HTMLElement {
    constructor() {
        super();
        const shadowRoot = this.attachShadow({ mode: 'open' });
        shadowRoot.innerHTML = this.template();
        

    init(){
       
    }
    template() {
        //这里编辑样式和内容
        return `
			<style>
					h1{
					color: #f00;
					}
					
			</style>
            <body>
                <div style="width: 175px;height: 179px;min-height: 179px;display: flex;flex-direction: column;position: relative;">
                </div>
            </body>    
		`;

    }
    // 生命周期:首次被插入文档DOM时
    connectedCallback() {
        console.log('template element is connected');
        //获取母页面传来的参数
        const tipMode = this.getAttribute('tipMode');
        
        //根据id获取当前页面元素
        var jy_btn = this.shadowRoot.getElementById("btn-on1");
        //修改元素样式
         jy_btn.style= "background-color: #ccc;"
        

       
        //为当前页面元素绑定事件
        this.shadowRoot.querySelector('#btn-on1').addEventListener('click', () => {

            
            var  objParams = {
                "speakMode":mySpeakMode,
                "userId":userName
            }
            var myEvent = new CustomEvent('jinyan', {
                // objParams就是需要传递的参数,
                // 可以是任意的类型
                detail: objParams
            });
            //发送通知,用于方法回调
            document.dispatchEvent(myEvent);

        });

        
    }
    // 生命周期:从文档DOM中删除时
    disconnectedCallback() {
        
    }
    // 生命周期:被移动到新的文档时
    adoptedCallback() {
       
    }

    // 生命周期:监听属性变化
    attributeChangedCallback() {
        
    }
}
customElements.define('hello-world', HelloWorld);

2、在需要使用该组件的页面中添加引用
 

<script type="module" src="./vendor/library/hello-world.js"></script>

创建元素时可以使用html,也可以使用js:
html:

<hello-world tipMode = "0"></hello-world>

js: 

let box = document.createElement("hello-world");
//传参
box.setAttribute('speakMode', '0')

3、在母页面中监听回调方法:

document.addEventListener('jiabin', (event) => {

    console.log(event.detail);
    
});


版权声明:本文为c_chang原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。