Skip to content

x-init

The x-init directive allows you to hook into the initialization phase of any element in Alpine.

This comes in handy when you want to fetch some data or do something, before the component is processed. For example:

html
<div
    x-data="{ posts: [] }"
    x-init="posts = await (await fetch('/posts')).json()"
>...</div>

Standalone

You can add x-init to any element inside or outside an x-data HTML block. For example:

html
<div x-data>
    <span x-init="console.log('I can initialize')"></span>
</div>
 
<span x-init="console.log('I can initialize too')"></span>

init() method

If the x-data object of a component contains an init() method, it will be called automatically. For example:

html
<div x-data="{
    init() {
        console.log('I am called automatically')
    }
}">
    ...
</div>

In case you have both an x-data object containing an init() method and an x-init directive, the x-data method will be called before the directive.

html
<div
    x-data="{
        init() {
            console.log('I am called first')
        }
    }"
    x-init="console.log('I am called second')"
    >
    ...
</div>