我正在创建两个自定义元素,它们都使用链接 rel="import"添加到 index.html 中。一种是带有插槽的容器,另一种是在插槽中放置数字的东西。这两个元素都有一个包含模板的 HTML 文件和一个指向将它们定义为自定义元素的 js 文件的链接。要将自定义元素类声明链接到我正在使用的 HTML 模板:
class PuzzlePiece extends HTMLElement{
constructor(){
super();
console.dir(document.currentScript);
const t = document.currentScript.ownerDocument.getElementById('piece-puzzle');
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(t.content.cloneNode(true));
}
这个拼图元素和容器可以正确渲染,并且当您手动将它们放入index.html light dom时,一切都可以正常工作
<special-puzzle id="grid">
<puzzle-piece id="hello"></puzzle-piece>
</special-puzzle>
但是,一旦我尝试在 index.html 中使用 JS 创建并附加拼图:
<script>
const addToGrid = document.createElement("puzzle-piece");
document.getElementById("grid").appendChild(addToGrid);
</script>
我在特殊拼图 Light dom 中看到一个新的拼图,但它不占用插槽,不渲染,并且控制台出现错误:
Uncaught TypeError: Cannot read property 'content' of null at new PuzzlePiece (puzzle-piece.ts:8) at HTMLDocument.createElement (:3:492) at (index):37
据我所知,问题是当使用 document.createElement 时,浏览器会进入类定义,但 document.currentScript.ownerDocument 与手动使用 HTML 标签时不同。我相信正因为如此,该组件找不到它的模板。这是我的第一个 Stack Overflow 问题,因此我们将不胜感激任何反馈/帮助!
最佳答案
感谢@Supersharp 和他们的 Stack Overflow post 解决了这个问题
基本上,为了保留正确的 document.currentScript.ownerDocument,我需要在类之前在 var 中声明它,然后在类中使用该 var。
旧:
class PuzzlePiece extends HTMLElement{
constructor(){
super();
const t = document.currentScript.ownerDocument.getElementById('piece-puzzle');
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(t.content.cloneNode(true));}
新:
var importedDoc = document.currentScript.ownerDocument;
class PuzzlePiece extends HTMLElement{
constructor(){
super();
const t = importedDoc.getElementById('piece-puzzle');
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(t.content.cloneNode(true));}
关于web-component - 自定义元素上的 createElement 破坏模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42617151/