點燈坊

うまく使いさえすれば、時間はいつも十分にある

Using $refs to Access the Element

Sam Xiao's Avatar 2022-01-25

$refs is just like document.getElementById or docuement.querySeletor to access the DOM element.

Version

Alpine 3.9

$refs

refs000

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 component
  • x-ref : set a name for the DOM element
  • $refs : a magic property that can be used to retrieve DOM elements marked with x-ref inside the component

Conclusion

  • x-ref in combination with $refs is a useful utility for easily accessing DOM elements directly

Reference

Alpine, $refs