我是Lit-Element的新手,在作为属性字符串传递时输出原始HTML时遇到问题。我猜想有更好的方法可以完成此操作,任何帮助将不胜感激。
JS Fiddle在这里显示我的问题: https://jsfiddle.net/32dnvkwq/
<script src="https://unpkg.com/@webcomponents/webcomponentsjs@next/webcomponents-loader.js"></script>
<script type="module">
import {LitElement, html} from 'https://unpkg.com/@polymer/lit-element@latest/lit-element.js?module';
class MyElement extends LitElement {
static get properties() {
return { str: String }
}
render() {
return html `${this.str}`;
}
}
customElements.define('my-element', MyElement);
</script>
<my-element str="line1<br />line2"></my-element>
输出:
line1<br />line2
答案 0 :(得分:2)
这是一个危险的操作,因此您必须明确选择允许allowint呈现HTML。确保您的HTML是安全的并且未被用户设置。您必须从lit-html导入unsafeHTML
directive并将this.str
包装在其中。
<script src="https://unpkg.com/@webcomponents/webcomponentsjs@next/webcomponents-loader.js"></script>
<script type="module">
import {LitElement, html} from 'https://unpkg.com/@polymer/lit-element@latest/lit-element.js?module';
import {unsafeHTML} from 'https://unpkg.com/lit-html@latest/directives/unsafe-html.js?module';
class MyElement extends LitElement {
static get properties() {
return { str: String }
}
render() {
return html `${unsafeHTML(this.str)}`;
}
}
customElements.define('my-element', MyElement);
</script>
<my-element str="line1<br />line2"></my-element>
答案 1 :(得分:0)
我想出了使用文档片段的解决方法。不确定它是否理想,但是否按预期工作。
JS Fiddle显示解决方案:https://jsfiddle.net/1whj0cdf/
<script src="https://unpkg.com/@webcomponents/webcomponentsjs@next/webcomponents-loader.js"></script>
<script type="module">
import {LitElement, html} from 'https://unpkg.com/@polymer/lit-element@latest/lit-element.js?module';
class MyElement extends LitElement {
static get properties() {
return { str: String }
}
returnString() {
var frag = document.createRange().createContextualFragment(`${ this.str }`);
return frag;
}
render() {
return html `${ this.returnString() }`;
}
}
customElements.define('my-element', MyElement);
</script>
<my-element str="line1<br />line2"></my-element>