Reputation: 3141
Working with Bootstrap 4.5/jquery 3.3 / alpinejs 2.2 I wonder if there is a way make 1 Main file and several small files, like components? It is possible to share data in this case?
Thanks!
Upvotes: 1
Views: 2707
Reputation: 3888
Alpine.js components don't have a built-in way to communicate between them.
However they can use the $dispatch
magic property to trigger custom events and use x-on:custom-event-name.window
or .document
to register listeners for window/document custom events.
Using that you can write multiple separate components and share information using custom events (you can find more patterns at https://codewithhugo.com/alpinejs-component-communication-event-bus/).
As to splitting into different files, there's no concept in Alpine.js of files/templates, if you're using a static site generator or a server-side templating engine, you can create partials and inject the markup in that fashion. Alpine.js is also fine evaluating new components injected into the HTML (using element.innerHTML
or the Alpine.js x-html
directive).
To share the Alpine.js "function components" you can put them into a .js
file, and load them with a regular <script src="path/to/file.js"></script>
, as long as the function is defined on the global scope, Alpine.js will have no problems running it.
Upvotes: 3