我们如何在标记库的帮助下使用 litElement 呈现 html 以创建 Web 组件

How do we render the html for creating a web component using litElement with the help of marked library

我的-element.ts

import marked from 'marked';

@customElement('my-element')
export class MyElement extends LitElement {
  constructor() {
    super();
    this.markdown = '<h2>Hello World</h2>';
  }

  @property()
  markdown;

  override render() {
    return html`${marked(this.markdown)}`;
  }
}

index.html

<my-element id="md"></my-element>

<script>
    document.getElementById('md').markdown = '## hello world';
</script>

在浏览器中,显示带有 HTML 标签

<h2 id="hello-world">hello world</h2>

enter image description here

Lit 希望您使用 unsafeHTML: https://lit.dev/docs/templates/directives/#unsafehtml
又一个依赖项……你可能不会 need/want shadowDOM

在原版中一切都简单多了JavaScript:

<script>
  customElements.define("marked-text", class extends HTMLElement {
    connectedCallback() {
      setTimeout( () => this.innerHTML = marked(this.innerHTML) )
    }
  })
</script>

<script src="//cdnjs.cloudflare.com/ajax/libs/marked/3.0.7/marked.min.js"></script>

<marked-text>
  # Hello Web Components
  Just great what you can do with **Vanilla** JavaScript!
</marked-text>

<style>
  marked-text strong { font-size:1.2em; color:green }
</style>