Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alpine.js - nested components

I have code like this with nested components:

<html>
<head>

<script src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/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.

like image 283
Marcin Nabiałek Avatar asked May 17 '20 11:05

Marcin Nabiałek


People also ask

Is Alpine JS lightweight?

Alpine. js is for developers who aren't looking to build a single page application (SPA). It's lightweight (~7kB gzipped) and designed to write markup-driven client-side JavaScript.

What is Alpinejs?

Alpine is a rugged, minimal tool for composing behavior directly in your markup. Think of it like jQuery for the modern web. Plop in a script tag and get going. Alpine is a collection of 15 attributes, 6 properties, and 2 methods.

Should I use Alpine JS?

It's best used when your project requires only minimal JavaScript, such as when you only need one or two components, like dropdowns, sidebars, tabs, and image selection. Alpine is also great for server-side rendered apps, such as Laravel, Rails, and AdonisJS, which require you to toggle some JavaScript components.


2 Answers

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.

like image 63
Hugo Avatar answered Sep 20 '22 11:09

Hugo


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.

like image 20
nektobit Avatar answered Sep 20 '22 11:09

nektobit