點燈坊

失くすものさえない今が強くなるチャンスよ

Using x-ref to Set a Name for the Element

Sam Xiao's Avatar 2022-01-25

Alpine’s x-ref is just like Vue’s v-ref. We can set a name for the DOM element.

x-ref

ref000

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, x-ref