The $component custom Alpine.js magic property
You can't add new directives to Alpine.js v2, but you can add custom magic properties. You know, the things that start with $
, like the $refs
, $dispatch
.
What caught my attention recently is the $component
that allows access to a different component's data. This property is provided by Magic Helpers, a collection of 3rd-party custom magic properties.
So far, the best solution to the global state management in Alpine.js is still Spruce, but using the $component
is a viable alternative if you sparingly want to access data from another component.
Here's how it works once you included the library:
<!-- Add the x-id, so you can reference it later -->
<div x-id="user" x-data="{ color: 'yellow' }"></div>
<p x-data>
My favorite color is
<!-- Reference the component by the x-id -->
<span x-text="$component('user').color"></span>
</p>
They also provide the conventient $parent
shortcut when you have nested components:
<div x-data="{ color: 'yellow' }">
<p x-data>
My favorite color is
<span x-text="$parent.color"></span>
</p>
</div>
There is a new version of Alpine.js, and the magic properties API changed. Consider this article outdated.