Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ffflabs/1ae361883ffbe5a15ccc8f8b6fc85e81 to your computer and use it in GitHub Desktop.
Save ffflabs/1ae361883ffbe5a15ccc8f8b6fc85e81 to your computer and use it in GitHub Desktop.
$component/$parent- AlpineJS Magic Helpers Demo
<div class="min-h-screen p-16 bg-gray-100">
<!-- Component 1 -->
<p class="mb-4 font-bold">The child component uses the color name set on the parent in x-text. Click the color name to update the parent component</p>
<div
x-data="{ color: 'blue' }"
class="w-64 h-64 mb-6 flex items-center justify-center"
:class="`bg-${color}-400`"
@click="color = color === 'blue' ? 'red' : 'blue'">
<!-- This p tag is a child component that can react to and set parent data -->
<p
x-data
x-text="$parent.color"
@click.stop="$parent.color = 'pink'"></p>
</div>
<!-- Component 2 -->
<p class="mb-4 font-bold">This component is the same as above, but also watches the third component's color as well</p>
<div
x-data="{ color: 'blue' }"
class="w-64 h-64 mb-6 flex items-center justify-center"
:class="`bg-${color}-300`"
@click="color = color === 'blue' ? 'red' : 'blue'">
<p
x-data
x-text="$component('yellowSquare').color"
@click.stop="$component('yellowSquare').color = 'pink'"
:class="`text-${$parent.color}-800`">
</p>
</div>
<!-- Component 3 -->
<p class="mb-4 font-bold">This watches a non-parent component. It requires adding an id attribute, or an `x-id` attribute so the component can be identified</p>
<div
id="yellowSquare"
x-data="{ color: 'yellow' }"
class="w-64 h-64"
:class="`bg-${color}-400`"
@click="color = color === 'yellow' ? 'green' : 'yellow'">
</div>
<p x-data x-text="$component('yellowSquare').color"></p>
</div>
<script src="https://cdn.jsdelivr.net/gh/alpine-collective/alpine-magic-helpers/dist/component.js"></script>
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js"></script>
[x-cloak] { display: none; }
<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment