Skip to content

x-data

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 for that component to reference.

State

State (JavaScript data that Alpine watches for changes) is at the core of everything you do in Alpine. State can be local (available within a chunk of HTML) or global (available anywhere on a page).

You can manage local state using x-data.

Data-less components

You can create an Alpine component without any data using x-data.

html
<!-- with empty object -->
<div x-data="{}">

<!-- without any value -->
<div x-data>

With data

You can also define the Alpine component with some data, that you can access within the component.

html
<!-- Don't worry about @click and x-show, they'll be covered later -->
<button x-data="{ open: true }" @click="open = false" x-show="open">
    Hide Me
</button>

Methods

Along with the state, you can also store methods and getters in x-data, as it's evaluated as a normal JavaScript object.

html
<div x-data="{ open: false, toggle() { this.open = ! this.open } }">
    <button @click="toggle()">Toggle Content</button>
 
    <div x-show="open">
        Content...
    </div>
</div>

NOTE

Notice the usage of this, to access state on the object itself.

You can also omit the calling parenthesis off of the method. For example:

html
<!-- Before -->
<button @click="toggle()">...</button>
 
<!-- After -->
<button @click="toggle">...</button>

Getters

JavaScript getters are like "computed properties". You can also include getters in x-data.

html
<div x-data="{
    open: false,
    get isOpen() { return this.open },
    toggle() { this.open = ! this.open },
}">
    <button @click="toggle()">Toggle Content</button>
 
    <div x-show="isOpen">
        Content...
    </div>
</div>

Scope

Properties defined in an x-data directive are available to all element children. Even ones inside other, nested x-data components.

html
<div x-data="{ foo: 'bar' }">
    <span x-text="foo"><!-- Will output: "bar" --></span>
 
    <div x-data="{ bar: 'baz' }">
        <span x-text="foo"><!-- Will output: "bar" --></span>
 
        <div x-data="{ foo: 'bob' }">
            <span x-text="foo"><!-- Will output: "bob" --></span>
        </div>
    </div>
</div>