javascript - 我想用 LitElement 渲染从我的网络服务器获得的一些 html 元素
问题描述
我想从网络服务器获取一些 HTML 元素,并使用 LitElement 在我的网络组件中呈现它们。我的元素在 MongoDB 中保存为字符串,例如<div> do something</div>
.
我已经使用 XMLHttpRequest 获取了元素,但无法将它们分配给我的属性并呈现它们。
import { LitElement, html } from 'lit-element';
class CassKomponent extends LitElement {
static get properties() {
return {
url: { type: String },
myArray: { type: Array },
};
}
constructor() {
super();
this.url = 'url';
this.myArray = [];
this.getResource;
}
render() {
return html`
<div id="check"></div>
<div>${this.url}</div>
<ul>
${this.myArray.map((i) => html`<li>${i}</li>`)}
</ul>
`;
}
getResource() {
var xhttp = new XMLHttpRequest();
xhttp.open('GET', this.url, true);
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
console.log(response);
//tried this one and it doesn't work
//document.querySelector('.heck').innerHTML = xhttp.responseText;
this.myArray = response;
}
};
xhttp.send();
}
}
customElements.define('cass-komponent', CassKomponent);
解决方案
编辑:
我误解了问题出在哪里,我错过了它在网络请求部分。
如果可能的话,我建议使用fetch()
instead XMLHttpRequest()
,因为它会使事情更容易编写......并且更容易调试。你会怎么想:
async getResource() {
let response = await fetch(this.url);
let jsonResponse = await response.json();
console.log(jsonResponse);
this.myArray =jsonResponse;
}
fetch()
有关MDN 网站的更多信息
如果你想渲染一个 HTML 元素(并且你确定它是安全的),你可以在你的渲染中使用来自 lit-html的unsafehtml
指令。
在您的渲染中,您可以使用:
render() {
return html`
<div id="check"></div>
<div>${this.url}</div>
<ul>
${this.myArray.map((i) => html`<li>${unsafeHTML(i)}</li>`)}
</ul>
`;
}
在您的情况下,这会是一个解决方案吗?
推荐阅读
- c - 在 c 中,宏 __FILE__、__LINE__ 和 __PRETTY_FUNCTION__ 是否分配内存?
- reactjs - 在 React Hooks 中动态设置状态时出错
- python - 如何减少 for 循环创建字典的运行时间
- android - adb 将文件从 /sdcard/ 复制到 /data/data/package 没有 root 权限
- postgresql - 数据库与 ORM 工具中的自动递增
- r - 将R中的数据框转换为其他格式
- c# - 如何在 Windows Installer 自定义对话框中将字段设为必填项
- java - 面板不想滚动
- java - 通知侦听器服务并不总是有效
- php - 带有插件过滤器的 Ajax 分页