我设法在一个表上实现了一种无限滚动。基本上,我只获取我需要显示的行以及一些额外的缓存。当我滚动时,我又添加了一些额外的行来填补空白。
我还需要一些调整,但它工作得很好。现在的问题是我需要在几个页面中实现逻辑,这需要大量的锅炉板。
我想知道这是否可能封装所有的东西在一个webcomponentvirtual-table
。是否有一种方法从控制器注入表的内容?
var Content = class Content {
// Models the table header, rows as well as methods to prepend or appends rows (when scrolling).
}
我尝试使用属性和fetch
内容中的控制器名称,但我看到的主要问题来自promise
,由于异步性,我似乎无法将其传递给类的内容成员。我最初使用了async / await
方法,但我不认为它对webcomponent有意义。
export default class VirtualTable extends HTMLElement {
static get observedAttributes() {
return ['controller'];
}
content = null;
constructor() {
super();
this.content = this.getContent(0); // Returns null!
}
getContent(index) {
var body = JSON.stringify({
Index: index
});
// Gets the content from the controller.
const fetchPromise = fetch(`${window.location.href}${this.controller}/GetContent/`, {
method: 'POST',
body: body,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8'
}
});
fetchPromise.then((response) => {
var jsonPromise = response.json();
jsonPromise.then((json) => {
return new Content(json); // Correctly instantiate the Content class.
});
});
}
}
<body>
<virtual-table controller="items">
</virtual-table>
</body>
<script type="module">
import VirtualTable from './scripts/VirtualTable.js'
customElements.define('virtual-table', VirtualTable);
</script>
有人有什么见解吗?
async/await
使代码更紧凑
导入的部件是而不是在constructor
阶段进行DOM更新;只有当connectedCallback
运行时,你才知道这些元素是在DOM中还是可以添加到DOM
因为constructor
可能不是async
(需要等待),你不能在那里做取回;您可以使用承诺的取回。
滚动部分由您决定…
customElements.define("json-table", class extends HTMLElement {
constructor(){
super().attachShadow({mode:"open"}).innerHTML =
`<table><thead>`+
`<tr><th>id</th><th>firstName</th><th>lastName</th></tr>`+
`<thead>` +
`<tbody></tbody>` +
`</table>`;
this.tbody = this.shadowRoot.querySelector("tbody");
}
async connectedCallback() {
let json = await (await fetch(this.getAttribute("endpoint"))).json();
json.users.forEach(user => this.add(user));
}
add(user){
let tr = document.createElement("tr");
tr.innerHTML = ["id","firstName","lastName"]
.map(key=>`<td>${user[key]}</td>`).join("");
this.tbody.append(tr);
}
})
<json-table endpoint='https://dummyjson.com/users' ></json-table>
在您要求<table>
中包含<slot>
元素之前(这是不能做到的),
请阅读并理解:https://github.com/WICG/webcomponents/issues/630