7

I have code like this with nested components:

<html>
<head>

<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js" defer></script>

</head>

<body>
  <div x-data="{isOpen: false}">
    <div x-data="{isOtherOpen: false}">
     
     
     <a href="#" @click="isOpen = !isOpen">Toogle element</a>

      <div x-show="isOpen">
        Now element is opened

      </div>


      <a href="#" @click="isOtherOpen = !isOtherOpen">Toogle other element</a>

      <div x-show="isOtherOpen">
        Now other element is opened
      </div>
      
    </div>
  </div>

</body>

</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:

<div x-data="{isOpen: false}">
   <div x-data="{isOtherOpen: false}">

into

<div x-data="{isOpen: false, isOtherOpen: false}">
   <div>

would solve the issue, but this way I would have single component.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291

3 Answers3

5

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.

Hugo
  • 3,500
  • 1
  • 14
  • 28
  • HI, Hugo how to correct this I'm new to alpine please help. ```
    – Nanda Sep 14 '20 at 11:00
  • for nav, i have 2 things one for mobile dropdown and the other is when scrolling change background – Nanda Sep 14 '20 at 11:02
4

Currently, in Alpine v2, if you nested a component inside another component, you would not be able to access the parent component easily. Now, in version 3 it's going to be a piece of cake :

<div x-data="{ firstName: 'John' }">
    <div x-data="{ lastName: 'Doe' }">
        <span x-text="firstName + ' ' + lastName"></span>
    </div>
</div>

Nested components are going to make communicating between components super duper easy . Expect to see this awesomeness available in the next version.

Hasan
  • 53
  • 6
nektobit
  • 843
  • 7
  • 11
2

nesting of alpine components is simple in 3.

But what you should really learn about in v3 is that they now have global state handling via https://alpinejs.dev/magics/store

https://alpinejs.dev/globals/alpine-store

those are the main takeaways

Toskan
  • 13,911
  • 14
  • 95
  • 185