$refs
is just like document.getElementById
or docuement.querySeletor
to access the DOM element.
Version
Alpine 3.9
$refs
Click Set focus
button to set focus on textbox.
<!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 x-data>
<input x-ref="textbox" />
<button @click="$refs.textbox.focus()">Set focus</button>
</body>
</html>
Line 9
<body x-data>
<input x-ref="textbox" />
<button @click="$refs.textbox.focus()">Set focus</button>
</body>
x-data
: define a componentx-ref
: set a name for the DOM element$refs
: a magic property that can be used to retrieve DOM elements marked withx-ref
inside the component
Conclusion
x-ref
in combination with$refs
is a useful utility for easily accessing DOM elements directly