[英]Looping through JSON object with Alpine JS in Lit 2.0 web component
I can't figure out how to loop through the connections object from fetch using x-for and Alpine JS to display the 2 records.我不知道如何使用 x-for 和 Alpine JS 从 fetch 中循环连接对象以显示 2 条记录。
I tried looping through ${this.connections} with x-for but got a "object Object" error.我尝试使用 x-for 循环 ${this.connections},但出现“对象对象”错误。
import { LitElement, html } from "../lit-all.min.js";
export class ContentDiv extends LitElement {
constructor() {
super();
this.connections;
}
static properties = {
connections: {},
};
connectedCallback() {
super.connectedCallback();
const dbPath = sessionStorage.getItem("dbPath");
fetch(`${dbPath}/connections/listConnections.php`, {
method: "POST",
headers: {
"Content-Type": "application/json",
}
})
.then((response) => {
return response.json();
})
.then((response) => {
this.connections = response;
});
}
createRenderRoot() {
return this;
}
render() {
return html`
<h1>Connections</h1>
<div>
<ul>
***Loop and display ${this.connections} here***
</ul>
</div>
`;
}
}
customElements.define("content-div", ContentDiv);
Is the the response coming as an array of objects?响应是否以对象数组的形式出现? It seems like that based on your comment.
根据您的评论,似乎是这样。
If so, I'd firstly instantiate this.connections
as an empty array in the constructor:如果是这样,我首先在构造函数中将
this.connections
实例化为一个空数组:
constructor() {
super();
this.connections = [];
}
And within render, you can do one of multiple ways of rendering an array in the template.在渲染中,您可以使用多种方式之一来渲染模板中的数组。
For instance, with plain JavaScript array method.例如,使用纯 JavaScript 数组方法。
render() {
return html`
<h1>Connections</h1>
<div>
<ul>
${this.connections.map((item) => html`<li>${item.connectionName}</li>`)}
</ul>
</div>
`;
}
You may also use the map()
built-in directive provided in the lit package.您还可以使用 lit 包中提供的
map()
内置指令。
import { LitElement, html, map } from "../lit-all.min.js";
...
render() {
return html`
<h1>Connections</h1>
<div>
<ul>
${map(this.connections, (item) => html`<li>${item.connectionName}</li>`)}
</ul>
</div>
`;
}
See https://lit.dev/docs/templates/lists/ for more information.有关更多信息,请参阅https://lit.dev/docs/templates/lists/ 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.