【问题标题】:How to use Custom Elements with template? [duplicate]如何将自定义元素与模板一起使用? [复制]
【发布时间】:2019-09-22 22:35:07
【问题描述】:

我试图了解 Web 组件是如何工作的,所以我尝试编写一个我在网络服务器上提供的小应用程序(在支持 rel="import") 的 Chrome 上测试:

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <link rel="import" href="my-app.html" />
  </head>
  <body>
    <my-app />
  </body>
</html>

my-app.html:

<template id="template">
  <div>Welcome to my app!</div>
</template>

<script>
class MyApp extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({mode: "open"});
    const template = document.getElementById("template");
    const clone = document.importNode(template.content, true);
    shadow.appendChild(clone);
  }
}
customElements.define("my-app", MyApp);
</script>

但它似乎不起作用。 &lt;my-app /&gt; 标记根本没有在 DOM 中呈现,我在控制台上收到此错误:

未捕获的类型错误:无法读取 null 的属性“内容”

我无法检索template 节点是什么?我做错了什么?

我还想知道的是,是否允许我编写没有样板代码(doctype、head、body...)的 HTML 文档,因为它是用来描述一个组件而不是整个文档按原样使用。 HTML5 规范是否允许它和/或它是否被大多数浏览器正确解释?

感谢您的帮助。

【问题讨论】:

  • 请注意 ` 正在消失,不应再使用。 ES6 模块是替换它的一种方式。
  • 是的,但是 IMO ES6 模块用于导入 JS 模块而不是 HTML。
  • 对。这意味着组件不再需要 &lt;template&gt; 标记。您可以创建一个 render() 函数,该函数返回一个模板文字字符串,该字符串可以嵌入您的数据或使用类似 npmjs.com/package/component-build-tools
  • 这让我有点难过。首先因为我更喜欢.vue文件语法而不是React的组件语法,其次因为render()方法返回的甚至不是JSX,它是一个模板字符串,这意味着不会有HTML的亮点你的 IDE 和所有东西。

标签: html web-component custom-element html-templates


【解决方案1】:

在模板内部时,不要使用document 全局:

<template id="template">
  <div>Welcome to my app!</div>
</template>

<script>
class MyApp extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({mode: "open"});

    // while inside the imported HTML, `currentDocument` should be used instead of `document`
    const currentDocument = document.currentScript.ownerDocument;
    // notice the usage of `currentDocument`
    const template = currentDocument.querySelector('#template');

    const clone = document.importNode(template.content, true);
    shadow.appendChild(clone);
  }
}
customElements.define("my-app", MyApp);
</script>

Plunker 演示:https://plnkr.co/edit/USvbddEDWCSotYrHic7n?p=preview



PS:Notes com 兼容性here,尽管我假设您知道 HTML 导入很快就会被弃用。

【讨论】:

  • 感谢您的快速回答。为什么要弃用 HTML 导入?有什么东西可以代替吗?
  • 如果您使用的是 chrome,请查看控制台:[Deprecation] HTML Imports 已弃用,将于 2019 年 3 月左右在 M73 中删除。请改用 ES 模块。有关详细信息,请参阅chromestatus.com/features/5144752345317376 目前的替代方案是 ES 模块。它更像是一个纯 JavaScript 解决方案。
  • 但是我们如何继续导入 HTML 模板呢?
  • 更多关于为什么在这里:polymer-project.org/blog/…。主要是因为该规范从未被主流浏览器统一实施,社区得出的结论是,在广泛采用之前它很糟糕。
  • 您确实想继续使用 html 模板,还是在询问“新最佳”替代方案?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-21
  • 1970-01-01
  • 2013-01-23
相关资源
最近更新 更多