如何将自定义元素与模板一起使用?

时间:2019-05-04 18:44:43

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

我试图了解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中呈现,我在控制台上收到此错误:

  

未捕获的TypeError:无法读取null的属性“ content”

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

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

谢谢您的帮助。

1 个答案:

答案 0 :(得分:1)

在模板内部时,请勿使用全局<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div class="container" id="clubs"> <div class="filter"> <label><input type="checkbox" v-model="selectedCategories" value="All" /> All</label> <label><input type="checkbox" v-model="selectedCategories" value="clubParking" /> Parking</label> <label><input type="checkbox" v-model="selectedCategories" value="clubToilets" /> Toilets</label> <label><input type="checkbox" v-model="selectedCategories" value="clubFloodlights" /> Floodlights</label> </div> <ul class="clubs-list"> <li v-for="club in filteredClubs">{{ club.clubName }}</li> </ul> </div>

document

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



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

相关问题