點燈坊

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

Using x-data for Single-element Component

Sam Xiao's Avatar 2022-02-11

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

single000

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 declare x-data directly on the element
  • x-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 declare x-data for single-element component. Just declare x-data on the element

Reference

Alpine, Single-element components