【问题标题】:error getting content from template customelement从模板自定义元素获取内容时出错
【发布时间】:2017-11-28 19:14:25
【问题描述】:

我有一个基本的 CustomElement,但我遇到了以下问题:

<template id="custom-element">
  <h1>Example 1</h1>
</template>

<script>

  class CustomElement extends HTMLElement {

    constructor() {
      super(); // always call super() first in the ctor.
      let shadowRoot = this.attachShadow({mode: 'open'});
      const template = document.querySelector('#custom-element');
      const instance = template.content.cloneNode(true);
      shadowRoot.appendChild(instance);
    }
    connectedCallback() {
      console.log("Connected");
    }

    disconnectedCallback() {

    }

    attributeChangedCallback(attrName, oldVal, newVal) {

    }
  }

  window.customElements.define('custom-element', CustomElement);

</script>

我在控制台中收到此错误:

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

这是因为const template总是null。这以前有效,但我不知道是否有任何改变,现在它不起作用。我正在使用 Chrome 版本 62.0.3202.94(官方版本)(64 位) 请问这方面有什么帮助吗?

【问题讨论】:

标签: javascript web-component shadow-dom custom-element


【解决方案1】:

试试这个:

<template id="custom-element">
  <style>
  h1 {
    color: red;
    font: bold 24px Tahoma;
  }
  </style>
  <h1>Example 1</h1>
</template>
<script>
  const template = (document.currentScript||document._currentScript).ownerDocument.querySelector('#custom-element').content;

  class CustomElement extends HTMLElement {
    constructor() {
      super(); // always call super() first in the ctor.
      let shadowRoot = this.attachShadow({mode: 'open'});
      let instance = template.cloneNode(true);
      shadowRoot.appendChild(instance);
    }
    connectedCallback() {
      console.log("Connected");
    }

    disconnectedCallback() {
    }

    attributeChangedCallback(attrName, oldVal, newVal) {
    }
  }

  window.customElements.define('custom-element', CustomElement);
</script>

您需要在构造函数之前到达document.currentScript||document._currentScript必须在导入的 HTML 文件的全局空间中访问。

我总是同时使用这两者来处理所有的 web 组件 polyfill。如果你不需要 polyfill,通过限制你支持的浏览器,你可以使用document.currentScript

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    相关资源
    最近更新 更多