【发布时间】: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>
但它似乎不起作用。 <my-app /> 标记根本没有在 DOM 中呈现,我在控制台上收到此错误:
未捕获的类型错误:无法读取 null 的属性“内容”
我无法检索template 节点是什么?我做错了什么?
我还想知道的是,是否允许我编写没有样板代码(doctype、head、body...)的 HTML 文档,因为它是用来描述一个组件而不是整个文档按原样使用。 HTML5 规范是否允许它和/或它是否被大多数浏览器正确解释?
感谢您的帮助。
【问题讨论】:
-
请注意 ` 正在消失,不应再使用。 ES6 模块是替换它的一种方式。
-
是的,但是 IMO ES6 模块用于导入 JS 模块而不是 HTML。
-
对。这意味着组件不再需要
<template>标记。您可以创建一个render()函数,该函数返回一个模板文字字符串,该字符串可以嵌入您的数据或使用类似 npmjs.com/package/component-build-tools -
这让我有点难过。首先因为我更喜欢
.vue文件语法而不是React的组件语法,其次因为render()方法返回的甚至不是JSX,它是一个模板字符串,这意味着不会有HTML的亮点你的 IDE 和所有东西。
标签: html web-component custom-element html-templates