在使用<template>和<slot>標簽定義的自定義組件中,子元素可以獲取作為自定義組件的父元素,然后使用此元素參考來訪問類定義的變數和函式。
但是,子元素如何知道哪個元素是自定義組件呢?
模板本身包含在影子 DOM 中。在頁面上呈現自定義組件時,此影子 DOM 會被克隆并作為其宿主附加到自定義組件中。
插入自定義組件的元素似乎無法告訴它附加到的節點樹來自被克隆的影子 DOM 節點,并且無法分辨當前 DOM 樹中的哪個元素是頂級自定義組件,除非它遍歷每個組件parentNode以檢查它們是否具有shadowRoot.
讓自定義組件內的子元素訪問自定義組件的類變數和函式的方法是什么?
customElements.define("my-comp", class extends HTMLElement {
creationTimestamp;
constructor() {
super();
let template = document.getElementById('my-template');
let templateContent = template.content;
const shadowRoot = this.attachShadow({
mode: 'open'
});
shadowRoot.appendChild(templateContent.cloneNode(true));
this.creationTimestamp = Date.now();
}
})
<html>
<template id="my-template">
I'm a new custom component using slots with value <slot name="slot1">default</slot>
<button onclick="console.log(this.parentNode.host.creationTimestamp)">Print timestamp at Template level</button>
</template>
<my-comp>
<span slot="slot1">
slotted value
<div>
<button onclick="console.log(this.parentNode.parentNode.parentNode.creationTimestamp)">Print timestamp</button>
</div>
</span>
</my-comp>
</html>
uj5u.com熱心網友回復:
我用于解耦的簡單規則是:
Parent to child:單向資料系結或

在下面的示例中,父級偵聽來自子級的事件并呼叫自身的函式以影響其狀態,或呼叫子級的函式以使它們執行某些操作。沒有一個孩子知道父母。

uj5u.com熱心網友回復:
現在我明白了。你想防止:
let timeStamp = this.parentNode.parentNode.parentNode.creationTimestamp;有多個 StackOverflow 答案可以解決這個問題:
讓孩子找到父母
控制:孩子模仿不刺穿shadowRoots的
標準JS ! 使用自定義函式:自定義元素 getRootNode.closest() 函式跨越多個(父)shadowDOM 邊界.closest(selector)closestElement(selector)
讓父母 告訴孩子一些事情
在控制中:
通過遞回潛入shadowRoots的父母:
如何獲取包含shadowRoot元素的檔案或節點中的所有HTML讓 parent回應child 的呼叫
控制: Child 都發送 Event,Parent 需要監聽
自定義事件通信的 Webcomponents 不能發送資料
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/452222.html標籤:javascript html dom 网络组件
