Reactive parent to child communication #2285
loomchild
started this conversation in
2. Show and tell
Replies: 1 comment 7 replies
-
I believe that tutorial was for v2. In v3, child components can read/write parent properties |
Beta Was this translation helpful? Give feedback.
7 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
I am trying to build a few simple reusable components for my site, and I am running into difficulties. I need to communicate some state bi-directionally between the parent and the child. This is needed for example when implementing an accordion question component, a spinner controlling number of input rows, etc.
It's easy to pass the value from child to parent via a custom event (e.g.:
@update="children[id] = $event.detail"
). However, I am struggling to pass the value from parent to child in a reactive manner. I know that this problem could be solved using the store, but I'd like to avoid that to keep the child components fully independent of the parent, to make them reusable in different contexts. In this video video there's a cool suggestion about using getters and setters, but it still requires the child component to access the parent state directly.Coming from Vue.js world, I'd love to have a
x-model
directive for custom components (more info, including syntax updated in Vue.js 3). In Alpine.js docs, I found information about dispatching tox-model
, but it seems to only pass the@input
event to the parent.Not being particularly bothered having to declare value and event separately instead of using a single
x-model
directive, I came up with the following solution using thex-effect
directive and partially inpired by Vue.js@update:field
event syntax (see this codepen for a complete live version):Could you tell me whether it makes sense in your opinion and if there are any better alternatives?
Thank you in advance!
Beta Was this translation helpful? Give feedback.
All reactions