1 minute, 15 seconds

Alpine Test XDATA

Everything in Alpine starts with the x-data directive.

x-data defines a chunk of HTML as an Alpine component and provides the reactive data (properties) for that component to reference.

Scope: Properties defined in an x-data directive are available to all element children.

Even ones inside other, nested x-data components.

Will output: "bar"
Will output: "bar"
Will output: "bob"
Expanded Content

x-data is evaluated as a normal JavaScript object, in addition to state, you can store methods and even getters.

Notice the added toggle() { this.open = ! this.open } method on x-data. This method can now be called from anywhere inside the component.

Content...
Delayed Toggle Contents

Notice the "Content" now depends on the isOpen getter instead of the open property directly.

In this case there is no tangible benefit. But in some cases, getters are helpful for providing a more expressive syntax in your components.

<div x-show="isOpen">
    Content...
</div>

Sometimes you may only have a single element inside your Alpine component, like the following:

Occasionally, you want to create an Alpine component, but you don't need any data. In these cases, you can always pass in an empty object.

Hello 👋

<button x-data="{ label: 'Click Here' }" x-text="label" x-on:click="label = 'Done!'"></button>
<div x-data="{ open: false }">
    <div x-data="{ label: 'Content:' }">
        <span x-text="label"></span>
        <span x-show="open"></span>
    </div>
</div>
<button x-data x-on:click="alert('I\'ve been clicked!')">Click Me</button>

Previous Next