Skip to content

Instantly share code, notes, and snippets.

@aazwar
Last active January 8, 2024 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aazwar/c367312a1458a118d437fb9b8c943d2b to your computer and use it in GitHub Desktop.
Save aazwar/c367312a1458a118d437fb9b8c943d2b to your computer and use it in GitHub Desktop.
Alpine JS accessing children x-data from parent
<!-- Parent Component -->
<div x-data="parent">
<div id="child1" x-data="{ childData: 'Hello from child 1' }">
<!-- Child 1 Content -->
</div>
<div id="child2" x-data="{ childData: 'Hello from child 2' }">
<!-- Child 2 Content -->
</div>
<!-- Accessing Child Data from Parent -->
<button @click="accessChildData()">Access Child Data</button>
</div>
<!-- Parent Component JavaScript -->
<script>
let parent = {
children: {},
init() {
this.$nextTick(() => {
Array.from(this.$el.querySelectorAll("[x-data]")).forEach(e => this.children[e.id] = Alpine.$data(e));
});
},
parentData: 'Hello from parent',
accessChildData() {
const child1Data = this.children.child1.childData;
const child2Data = this.children.child2.childData;
console.log("Child 1 Data:", child1Data);
console.log("Child 2 Data:", child2Data);
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment