Last active
January 8, 2024 06:49
-
-
Save aazwar/c367312a1458a118d437fb9b8c943d2b to your computer and use it in GitHub Desktop.
Alpine JS accessing children x-data from parent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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