I have code like this with nested components:
JavaScript
x
32
32
1
<html>
2
<head>
3
4
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js" defer></script>
5
6
</head>
7
8
<body>
9
<div x-data="{isOpen: false}">
10
<div x-data="{isOtherOpen: false}">
11
12
13
<a href="#" @click="isOpen = !isOpen">Toogle element</a>
14
15
<div x-show="isOpen">
16
Now element is opened
17
18
</div>
19
20
21
<a href="#" @click="isOtherOpen = !isOtherOpen">Toogle other element</a>
22
23
<div x-show="isOtherOpen">
24
Now other element is opened
25
</div>
26
27
</div>
28
</div>
29
30
</body>
31
32
</html>
but it seems it does not work. Is there any why to make it work using nested components or maybe Alpine.js cannot handle this yet? OF course I’m aware that changing:
JavaScript
1
3
1
<div x-data="{isOpen: false}">
2
<div x-data="{isOtherOpen: false}">
3
into
JavaScript
1
3
1
<div x-data="{isOpen: false, isOtherOpen: false}">
2
<div>
3
would solve the issue, but this way I would have single component.
Advertisement
Answer
Alpine.js doesn’t support nesting as of v2.x latest.
If you don’t want to combine everything into a single component, you can have 2 components side by side and you can setup communication between them with $dispatch
to send custom events and x-on:custom-event.window
to listen to the event.