126 lines
2.2 KiB
Markdown
126 lines
2.2 KiB
Markdown
# Alpine.js Documentation - Directives
|
|
|
|
Alpine directives are attributes that you can add to HTML elements to give them special behavior.
|
|
|
|
## [x-init](/directives/init)
|
|
|
|
The `x-init` directive allows you to hook into the initialization phase of any element in Alpine.
|
|
|
|
```
|
|
<div x-init="console.log('I\'m being initialized!')"></div>
|
|
```
|
|
|
|
In the above example, "I'm being initialized!" will be output in the console before it makes further DOM updates.
|
|
|
|
Consider another example where `x-init` is used to fetch some JSON and store it in `x-data` before the component is processed.
|
|
|
|
```
|
|
<div
|
|
|
|
x-data="{ posts: [] }"
|
|
|
|
x-init="posts = await (await fetch('/posts')).json()"
|
|
|
|
>...</div>
|
|
```
|
|
|
|
### [$nextTick](#next-tick)
|
|
|
|
Sometimes, you want to wait until after Alpine has completely finished rendering to execute some code.
|
|
|
|
This would be something like `useEffect(..., [])` in react, or `mount` in Vue.
|
|
|
|
By using Alpine's internal `$nextTick` magic, you can make this happen.
|
|
|
|
```
|
|
<div x-init="$nextTick(() => { ... })"></div>
|
|
```
|
|
|
|
### [Standalone `x-init`](#standalone-x-init)
|
|
|
|
You can add `x-init` to any elements inside or outside an `x-data` HTML block. For example:
|
|
|
|
```
|
|
<div x-data>
|
|
|
|
|
|
n<span x-init="console.log('I can initialize')"></span>
|
|
|
|
|
|
n</div>
|
|
|
|
|
|
n<span x-init="console.log('I can initialize too')"></span>
|
|
```
|
|
|
|
### [Auto-evaluate init() method](#auto-evaluate-init-method)
|
|
|
|
If the `x-data` object of a component contains an `init()` method, it will be called automatically. For example:
|
|
|
|
```
|
|
<div x-data="{"
|
|
|
|
|
|
ninit() {
|
|
|
|
|
|
nconsole.log('I am called automatically')
|
|
|
|
|
|
n}
|
|
|
|
|
|
n}"
|
|
|
|
>...
|
|
|
|
</div>
|
|
```
|
|
|
|
This is also the case for components that were registered using the `Alpine.data()` syntax.
|
|
|
|
```
|
|
Alpine.data('dropdown', () => ({
|
|
|
|
|
|
ninit() {
|
|
|
|
|
|
nconsole.log('I will get evaluated when initializing each "dropdown" component.')
|
|
|
|
|
|
n},
|
|
|
|
|
|
n}))
|
|
```
|
|
|
|
If 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.
|
|
|
|
```
|
|
<div
|
|
|
|
x-data="{"
|
|
|
|
|
|
ninit() {
|
|
|
|
|
|
nconsole.log('I am called first')
|
|
|
|
|
|
n}
|
|
|
|
|
|
n}"
|
|
|
|
x-init="console.log('I am called second')"
|
|
|
|
>
|
|
|
|
...
|
|
|
|
</div>
|
|
```
|
|
|
|
Code highlighting provided by [Torchlight](https://torchlight.dev/) |