1 回答

TA貢獻1794條經驗 獲得超7個贊
constructor
永遠無法創建在中設置 DOM 內容的自定義元素document.createElement()
您將看到許多示例(包括我的示例),其中 DOM 內容是在構造函數中設置的。
這些元素永遠無法創建document.createElement
說明(HTML DOM API):
當您使用時:
<todo-card content=FOO></todo-card>
該元素(從 HTMLElement 擴展)具有所有 HTML 接口(它在 HTML DOM 中),
您可以在構造函數中設置 innerHTML
但是,當你這樣做時:
document.createElement("todo-card");
構造函數在沒有 HTML 接口的情況下運行(元素可能與 DOM 無關),因此在構造函數
中設置 innerHTML會產生錯誤:
未捕獲的 DOMException:無法構造“CustomElement”:結果不得有子項
來自https://html.spec.whatwg.org/multipage/custom-elements.html#custom-element-conformance:
該元素不得獲得任何屬性或子元素,因為這違反了使用 createElement 或 createElementNS 方法的消費者的期望。一般來說,工作應該盡可能推遲到 connectedCallback
shadowDOM 是一個 DOM
使用shadowDOM時,您可以在構造函數中設置shadowDOM內容:
constructor(){
super().attachShadow({mode:"open"})
.innerHTML = `...`;
}
正確的代碼(沒有 shadowDOM):使用connectedCallback:
<todo-card content=FOO></todo-card>
<script>
window.customElements.define(
"todo-card",
class extends HTMLElement {
constructor() {
super();
//this.innerHTML = this.getAttribute("content");
}
connectedCallback() {
this.innerHTML = this.getAttribute("content");
}
}
);
try {
const todo = document.createElement("todo-card");
todo.setAttribute("content", "BAR");
document.body.appendChild(todo);
} catch (e) {
console.error(e);
}
</script>
您還有另一個小問題:content
是默認屬性,FireFox 不會停止警告您:
或者不使用 createElement
const todo = document.createElement("todo-card");
todo.setAttribute("content", "BAR");
document.body.appendChild(todo);
可以寫成:
const html = `<todo-card content="BAR"></todo-card`;
document.body.insertAdjacentHTML("beforeend" , html);
可以connectedCallback運行多次!
當你四處移動 DOM 節點時:
<div id=DO_Learn>
<b>DO Learn: </b><todo-card todo="Custom Elements API"></todo-card>
</div>
<div id="DONT_Learn">
<b>DON'T Learn!!! </b><todo-card todo="React"></todo-card>
</div>
<script>
window.customElements.define(
"todo-card",
class extends HTMLElement {
connectedCallback() {
let txt = this.getAttribute("todo");
this.append(txt);// and appended again on DOM moves
console.log("qqmp connectedCallback\t", this.parentNode.id, this.innerHTML);
}
disconnectedCallback() {
console.log("disconnectedCallback\t", this.parentNode.id , this.innerHTML);
}
}
);
const LIT = document.createElement("todo-card");
LIT.setAttribute("todo", "Lit");
DO_Learn.append(LIT);
DONT_Learn.append(LIT);
</script>
LIT 的 connectedCallback 運行
移動 LIT 時
disconnectedCallback 運行(注意父級!元素已經在新位置)
LIT 的 connectedCallback 再次運行,再次
"Learn Lit"
追加
這取決于你的程序員你的組件/應用程序必須如何處理這個
Web 組件庫
像 Lit、HyperHTML 和 Hybrids 這樣的庫實現了額外的回調來幫助解決所有這些問題。
我建議先學習自定義元素 API,否則你學習的是工具而不是技術。
有工具的傻瓜,仍然是傻瓜
添加回答
舉報