简体   繁体   English

如何在我的自定义元素中分离 HTML 标记?

[英]How do I separate the HTML markup in my custom element?

I have a custom element that displays a message inside three nested divs:我有一个自定义元素,它在三个嵌套的 div 中显示一条消息:

class HelloWorld extends HTMLElement {
    connectedCallback() {
        const div1 = document.createElement('div')
        this.appendChild(div1)
        
        const div2 = document.createElement('div')
        div1.appendChild(div2)
        
        const div3 = document.createElement('div')
        div3.textContent = 'Hello World!';
        div2.appendChild(div3)
    }
}
customElements.define('hello-world', HelloWorld)

It works, but I'm not happy with having all of the HTML markup inside of strings.它有效,但我对在字符串中包含所有 HTML 标记不满意。 I want to separate the HTML markup from the JavaScript, preferably in a separate file so that my IDE can give me better support.我想将 HTML 标记与 JavaScript 分开,最好放在单独的文件中,以便我的 IDE 可以给我更好的支持。 Here's an example of how I want to separate them:这是我想如何将它们分开的示例:

<div>
    <div>
        <div id="inner-div"></div>
    </div>
</div>
class HelloWorld extends HTMLElement {
    connectedCallback() {
        const innerDiv = this.getElementById('inner-div')
        innerDiv .textContent = 'Hello World!';
    }
}
customElements.define('hello-world', HelloWorld)

Is it possible to separate them like this?是否可以像这样将它们分开?

There was a way to achieve this in the past, but it was removed from the specification, and subsequently, from browsers as well (eg Chrome removed it in Chrome 70).过去有一种方法可以实现这一点,但它已从规范中删除,随后也从浏览器中删除(例如,Chrome 在 Chrome 70 中将其删除)。 It was called HTML imports and it originally was part of the web components specs.它被称为HTML imports ,最初是 web 组件规格的一部分。

Currently they are working on a replacement for this obviously lacking platform feature, which will be called HTML modules .目前,他们正在努力替代这个明显缺乏的平台功能,称为HTML modules Here's the explainer .这是解释器 Chances are the syntax is going to look similar to this:语法可能看起来类似于:

  import {content} from "import.html";

Resolving the remaining issues with HTML modules I assume might take quite some time, so until then the only viable option you have is to have either your build stack resolve the issue for you (eg with webpack-raw-loader), or to rely on async fetch to get the job done (which might result in a less-than-optimal performance experience).我认为解决 HTML 模块的剩余问题可能需要相当长的时间,因此在此之前,您唯一可行的选择是让您的构建堆栈为您解决问题(例如使用 webpack-raw-loader),或者依赖异步fetch以完成工作(这可能会导致性能体验不佳)。

We already have JSON modules and CSS module scripts (which both were sorely missing features for a long time as well).我们已经有了JSON 模块CSS 模块脚本(它们在很长一段时间内都非常缺少功能)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM