webcomponent 中的子元素
Child elements in webcomponent
假设我们有一个自定义元素以这种方式使用:
<list-image>
<img src="" />
....
</list-image>
其中list-image以滑块方式显示img标签。
如果组件的用户插入带有
的 img 标签
document.querySelector('list-image').insertAdjacentHTML('beforeend', '<img src="..." />');
组件是否可以知道新元素img?
解决方案是在 <list-image>
自定义元素本身上使用 MutationObserver。
在connectedCallback()
方法中,观察子元素的变化:
customElements.define('list-image', class extends HTMLElement {
connectedCallback() {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
//Detect <img> insertion
if (mutation.addedNodes.length)
console.info('Node added: ', mutation.addedNodes[0])
})
})
observer.observe(this, { childList: true })
}
})
function add() {
document.querySelector('list-image')
.insertAdjacentHTML('beforeend', '<img alt="TOTO" />')
}
<list-image>
<img alt="Image1">
<img alt="Image2">
</list-image>
<button onclick="add()">Add image</button>
从该页面更新:https://developers.google.com/web/fundamentals/web-components/examples/howto-tabs
New children will get slotted automatically and cause slotchange to
fire, so not MutationObserver is needed.
假设我们有一个自定义元素以这种方式使用:
<list-image>
<img src="" />
....
</list-image>
其中list-image以滑块方式显示img标签。 如果组件的用户插入带有
的 img 标签document.querySelector('list-image').insertAdjacentHTML('beforeend', '<img src="..." />');
组件是否可以知道新元素img?
解决方案是在 <list-image>
自定义元素本身上使用 MutationObserver。
在connectedCallback()
方法中,观察子元素的变化:
customElements.define('list-image', class extends HTMLElement {
connectedCallback() {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
//Detect <img> insertion
if (mutation.addedNodes.length)
console.info('Node added: ', mutation.addedNodes[0])
})
})
observer.observe(this, { childList: true })
}
})
function add() {
document.querySelector('list-image')
.insertAdjacentHTML('beforeend', '<img alt="TOTO" />')
}
<list-image>
<img alt="Image1">
<img alt="Image2">
</list-image>
<button onclick="add()">Add image</button>
从该页面更新:https://developers.google.com/web/fundamentals/web-components/examples/howto-tabs
New children will get slotted automatically and cause slotchange to fire, so not MutationObserver is needed.