2

我正在創建兩個自定義元素,兩者都使用鏈接rel =「import」添加到index.html。一個是帶有插槽的容器,另一個是將數字放入插槽的東西。兩個元素都有一個帶有模板的HTML文件和一個指向js文件的鏈接,將它們定義爲自定義元素。要自定義元素類聲明鏈接到HTML模板,我使用:createElement自定義元素中斷模板

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的光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> 

我看到一個新的難題片在特殊的難題光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標記不同。我相信因爲這個,組件找不到它的模板。這是我的第一個堆棧溢出問題,所以任何反饋/幫助將不勝感激!

+0

這裏是[github上]代碼(https://github.com/arjunyel/special-puzzle) –

+2

看看這個回答:http://stackoverflow.com/a/42093412/4600982 – Supersharp

+2

或這一個:http://stackoverflow.com/a/41409299/4600982 – Supersharp

回答

2

解決了感謝真棒@Supersharp及其Stack Overflow post

基本上,爲了保持正確的document.currentScript.ownerDocument我需要在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));}