在Vanilla JS中为单个页面创建可重用的Web组件?

我有一个HTML页面,该页面使用jQuery创建表以获取数据,并使用普通JavaScript来创建表。我想为我的设置表创建方法创建一个类,以便可以将其导出并在整个HTML代码中重复使用。我在这里吗?

当前表创建代码

public LinkedHashMap<String,LinkedHashMap<String,String>> details;

我在想的是在另一个.js文件中的样子

function(data) {
                //Rename the variable so I can reuse some code 
                var data_list = data.dataList;
                //Headers for our tables second row
                var titles = data.headers;
                //HTML table variables
                var perRow = 2,html = "<table><tr>";
                //Loop through our array of data
                for (var i = 0; i < data_list.length; i++) {
                    //Add our header first,as we want that to appear first
                    html += "<td>" + titles[i]+ "</td>";
                    //Then add the correct data piece for the header
                    html += "<td>" + data_list[i]+ "</td>";
                    //Break into the next row
                    var next = i+1;
                    if (next % perRow == 0 && next != data_list.length) {
                        //Start new row
                        html += "</tr><tr>";
                    }
                }
                //End the table
                html += "</tr><table>";
                //Attach the table to the HTML doc when finished
                document.getElementById("container").innerHTML = html;
            };

我走对了吗?我应该只使用一个功能吗?如果我在同一目录中包含其.js文件,则此类可以正常工作吗?在学习框架之前,我只想使用一些OOP原理来制作自己的Web组件。

kakasned 回答:在Vanilla JS中为单个页面创建可重用的Web组件?

理想情况下,应该有一个shadowRoot,其中带有用于元素html的插槽,否则可以将表插入shadowRoot中。此示例将通过广告位定位HTML:

HTML(静态页面或其他内容)中的

包括以下内容:<data-grid>data-grid</data-grid>

在已加载模块中,通过导入或脚本type = module:

/*
this is an example to show basics,it's not ideal,however it answers the question with a working example
*/
class DataTable extends HTMLElement {
    constructor() {
        super();
        // static,or request,or setup default and update later...
        this.dataList = [[1,2],[7,9]];
        this.dataHeaders = ['one','two'];

        // only work with shadowRoot in constructor,never the HTML element
        // minimize work here too,do that later in lifecycle callbacks
        this.attachShadow({mode:'open'}).innerHTML = `
<!-- NOTE how this th styling doesn't work because the table is rendered into the HTML,not the shadowRoot -->
<style>
/* styles shadow content in the host */
:host th{text-align:left;color:blue;}
/* only top-level selectors */
::slotted(table){text-align:right;}
</style>
<table style="width:100%;"><tr><th>ok</th></tr></table>
<button>update table</button>
<slot></slot>
        `;
        this.shadowRoot.querySelector('button').addEventListener('click',this.updateTable.bind(this));
    }
    connectedCallback(){
    // change attributes,html,etc here
        this.createTable();
    }
    random(){
        const max=Date.now();
        return Math.floor(Math.random() * Math.floor(max));
    }
    updateTable(){
        this.dataList = this.dataList.map((row,i)=>{
            return row.map(this.random);
        });
        this.createTable();
    }
    createTable() {
        // use the render cycle
        cancelAnimationFrame(this._createTable);
        this._createTable = requestAnimationFrame(()=>{
        // html will go into the shadowRoot slot (default or whatever is targeted)
        this.innerHTML = `
<table>
<thead><tr>
    ${ this.dataHeaders.reduce((html,col,i)=>{
        return html + `<th>${i+1} ${col}</th>`;
    },'') }
</tr></thead>
<tbody>
<tr>${ this.dataList.map((row,i)=>{
    return `<td>${ row.join('</td><td>') }</td>`;
}).join('</tr><tr>') }</tr>
</tbody>
</table>
        `;
        });
    }
}
// define the element,if not already
customElements.get('data-grid') || customElements.define('data-grid',DataTable);

查看有效的examplecommit)和Web Components best-practices的Google Web Developer文档。

本文链接:https://www.f2er.com/3165998.html

大家都在问