使用LitElement渲染服务器获取的HTML字符串问题求助
解决LitElement渲染服务器HTML字符串的问题
我看了你的代码,这里有几个关键问题导致你没法正确渲染从服务器获取的内容,咱们一步步来修复:
- 方法调用没执行:构造函数里你写的是
this.getResource;,这只是引用了方法,并没有触发执行,得改成this.getResource();,这样组件初始化时才会发起请求。 - 回调里的
this指向错了:XMLHttpRequest的onreadystatechange回调里,默认this指向的是xhttp对象,不是你的组件实例,所以this.myArray = response;根本没更新组件的属性。解决办法是用箭头函数,让this继承外部的组件上下文:xhttp.onreadystatechange = () => { if (xhttp.readyState == 4 && xhttp.status == 200) { const response = JSON.parse(xhttp.responseText); this.myArray = response; } }; - HTML字符串被转义了:LitElement默认会把所有文本内容转义(防止XSS),但如果你确实需要渲染原始HTML,得用Lit提供的
unsafeHTML指令。首先要导入它:
然后在渲染时用import { LitElement, html, unsafeHTML } from 'lit-element';unsafeHTML()包裹你的HTML字符串:${this.myArray.map((item) => html`<li>${unsafeHTML(item)}</li>`)} - 别直接操作DOM:你之前试的
document.querySelector('.heck').innerHTML不仅写错了选择器(元素id是check不是类heck),而且在LitElement里直接操作DOM是不推荐的,Lit的核心是用属性和模板驱动视图,完全不需要手动改DOM。
下面是修正后的完整代码:
import { LitElement, html, unsafeHTML } from 'lit-element'; class CassKomponent extends LitElement { static get properties() { return { url: { type: String }, myArray: { type: Array }, }; } constructor() { super(); this.url = 'your-api-url-here'; // 替换成你的实际接口地址 this.myArray = []; this.getResource(); // 这里必须加括号调用方法 } render() { return html` <div id="check"></div> <div>${this.url}</div> <ul> ${this.myArray.map((item) => html`<li>${unsafeHTML(item)}</li>`)} </ul> `; } getResource() { const xhttp = new XMLHttpRequest(); xhttp.open('GET', this.url, true); // 箭头函数保证this指向组件实例 xhttp.onreadystatechange = () => { if (xhttp.readyState == 4 && xhttp.status == 200) { const response = JSON.parse(xhttp.responseText); console.log(response); this.myArray = response; // 现在能正确更新组件属性了 } }; xhttp.send(); } } customElements.define('cass-komponent', CassKomponent);
⚠️ 提醒:使用unsafeHTML一定要谨慎,确保你获取的HTML内容是完全可信的,避免遭遇XSS攻击。如果内容来自不可信来源,一定要先做过滤处理。
内容的提问来源于stack exchange,提问作者Ebian
相关产品推荐
相关产品推荐

