首页 > 解决方案 > 我想用 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);

标签: javascriptlit-element

解决方案


编辑:

我误解了问题出在哪里,我错过了它在网络请求部分。

如果可能的话,我建议使用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>
    `;
  }

在您的情况下,这会是一个解决方案吗?


推荐阅读