Alpine’s x-init
is just like Vue’s mounted
hook. We can run some expressions in x-init
.
Version
Alpine 3.8
x-init
The textbox is focused on page loads.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://unpkg.com/alpinejs" defer></script>
<title>Alpine</title>
</head>
<body>
<input x-data x-init="$el.focus()" />
</body>
</html>
Line 10
<input x-data x-init="$el.focus()" />
x-data
: make the current element as a single-element componentx-init
: run expressions on initialization phase of the component$el
: retrieve the current DOM element
Conclusion
- Not only can we initialize the data in
x-init
, but also we can run expressions inx-init