![](/img/trans.png)
[英]“shadowRoot.querySelector” not working with lit-element in Web Components
[英]Insert a node inside html rendering with lit-element web components
作为练习,给定一个html标记和重复次数 ( n ),我想使用lit-element web 组件插入n次标记节点。 我堆在这里:
import {LitElement, html, css} from 'lit-element';
export class WebComponent extends LitElement {
static get properties() {
return {
node: {type: String},
repetitions: {type: Number}
}
};
constructor() {
super();
this.node = "";
this.repetitions = 0;
}
render() {
var node = document.createElement(this.node);
return html`
<div>
${for (i = 0; i < this.repetitions; i++) {
// Insert node here
}}
</div>
`;
};
}
customElements.define('web-component', WebComponent);
这可能吗? 如何?
是的!
您正在寻找的可能是 'unsafeHTML',在 package 'lit-html/directives/unsafe-html' 中可用;
从 lit-html 网站:
import {unsafeHTML} from 'lit-html/directives/unsafe-html.js';
const markup = '<div>Some HTML to render.</div>';
const template = html`
Look out, potentially unsafe HTML ahead:
${unsafeHTML(markup)}
`;
在您的示例中,可以这样使用:
render() {
return html`
<div>
${(() => {
let htmlString = '';
for (i = 0; i < this.repetitions; i++) {
htmlString += `<${this.node}>Custom Node!</${this.node}>`;
}
return html`${unsafeHTML(htmlString)}`;
})()}
</div>
`;
};
正如 function 名称所示,使用时要小心!
同样来自 lit-html 网站:
请注意,这对于任何未经清理或转义的用户提供的输入都是不安全的,因为它可能导致跨站点脚本漏洞。
经过测试,它适用于最新版本!
不能告诉你的版本,但这似乎已经存在了一段时间,所以你应该很好!
https://lit.dev/docs/templates/directives/#unsafehtml
import {unsafeHTML} from 'lit/directives/unsafe-html.js';
[...]
this.myhtml = "one<br />two"
[...]
render() {
return html`
<div>
${unsafeHTML(this.myhtml)}
</div>
`
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.