Replies: 2 comments
-
This is something that you should handle with a server side templating engine, or even a front end one. |
Beta Was this translation helpful? Give feedback.
0 replies
-
Yes, is it possible. <template x-component="dropdown">
<div x-data="{ ...dropdown(), ...$el.parentElement.data()}">
<button x-on:click="open">Open</button>
<div x-show="isOpen()" x-on:click.away="close" x-text="content"></div>
</div>
</template>
<x-dropdown content="Content for my first dropdown"></x-dropdown>
<div> Random stuff... </div>
<x-dropdown content="Content for my second dropdown"></x-dropdown>
<x-dropdown></x-dropdown>
<script>
function dropdown() {
return {
show: false,
open() { this.show = true },
close() { this.show = false },
isOpen() { return this.show === true },
content: 'Default content'
}
}
document.querySelectorAll('[x-component]').forEach(component => {
const componentName = `x-${component.getAttribute('x-component')}`
class Component extends HTMLElement {
connectedCallback() {
this.append(component.content.cloneNode(true))
}
data() {
const attributes = this.getAttributeNames()
const data = {}
attributes.forEach(attribute => {
data[attribute] = this.getAttribute(attribute)
})
return data
}
}
customElements.define(componentName, Component)
})
</script> |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
The docs mention you can extract data and behavior into reusable functions, but can you reuse the HTML too?
For example, if I want to use a dropdown twice in different places in the same page, do I need to repeat the HTML like this:
Beta Was this translation helpful? Give feedback.
All reactions