Sometimes we may only have a single element inside our Alpine component, and we can declare x-data
directly on the single element.
Version
Alpine 3.8
x-data
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
: since<input>
is the only element inside component, wen can declarex-data
directly on the elementx-init
: run expressions on initialization phase of the component$el
: retrieve the current DOM element
Conclusion
- We don’t have to add outer
<div>
to declarex-data
for single-element component. Just declarex-data
on the element