如何解决自定义元素仅渲染一次
我希望能够创建可重复使用的自定义元素。在我当前的实现中,每个自定义元素只呈现一次。所有元素(全部 4 个)都注入到 DOM 中,但仅呈现每个元素的第一个实例。
我尝试过使用 ShadowDOM 和不使用它。有什么想法吗?
index.html
(摘自 <body>
):
<body>
<funky-header></funky-header>
<funky-content></funky-content>
<funky-header></funky-header>
<funky-content></funky-content>
<script src="index.js" defer></script>
</body>
我创建了一个通用脚本来从 .html 文件创建自定义元素:
index.js
:
const elements = [
{ name: 'funky-header',shadowDom: false },{ name: 'funky-content',shadowDom: false }
]
async function registerCustomElement(elementName,shadowDom) {
console.log(`Registering ${elementName}`)
await fetch(`./${elementName}.html`)
.then(stream => stream.text())
.then(async markup => {
const doc = new DOMParser().parseFromString(markup,'text/html');
const template = doc.querySelector('template[alpine]')
const templateContent = template.content
const styles = doc.querySelector('style[scoped]')
const styleContent = styles.textContent.toString()
const elements = templateContent.querySelectorAll('[class]')
class CustomElement extends HTMLElement {
constructor() {
super()
}
connectedCallback() {
console.log(`inserting ${elementName}`)
if (shadowDom) {
const shadowRoot = this.attachShadow({ mode: 'closed' })
shadowRoot.appendChild(template.content)
} else {
this.setAttribute(`data-x-${elementName}`,'')
elements.forEach(element => {
element.setAttribute(`data-x-${elementName}`,'')
})
const scopedStyles = styleContent.replaceAll(' {','{').replaceAll('{',`[data-x-${elementName}] {`)
const styleTag = document.createElement('style')
styleTag.type = 'text/css'
styleTag.append(document.createTextNode(scopedStyles))
this.append(styleTag)
this.append(templateContent)
}
}
}
customElements.define(elementName,CustomElement)
})
.catch(err => {
console.log('ERROR:',err)
})
}
elements.forEach(element => registerCustomElement(element.name,element.shadowDom))
示例模板文件:
funky-header.html
:
<template alpine>
<h1 class="font-black text-blue-800">This is my header</h1>
<p class="font-thin text-xs text-blue-600 my-text">This is a paragraph with a longer text,to simualte a descritpion.</p>
</template>
<style scoped>
.my-text {
color: purple;
}
</style>
解决方法
解决方案就像用 this.append(templateContent)
替换 this.innerHTML = template.innerHTML
一样简单。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。