點燈坊

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

Using init() without x-init

Sam Xiao's Avatar 2022-02-12

We can also provide init() in the x-data Object, and it will be called automatically without the x-init directive.

Version

Alpine 3.8

x-init

init000

After Alpine has finished rendering, console.log the element’s value.

<!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="{ message: 'Alpine Rocks' }"
      x-model="message"
      x-init="$nextTick(() => console.log($el.value))"
    />
  </body>
</html>

Line 10

<input
  x-data="{ message: 'Alpine Rocks' }"
  x-model="message"
  x-init="$nextTick(() => console.log($el.value))"
/>
  • x-data : define a variable for two-way data binding on <input>
  • x-model : two-way data binding the input value to a variable
  • x-init : run expressions on initialization phase of the component
  • $nextTick : run expressions after rendering to get the value of the element
  • $el : retrieve the current DOM element

init()

init000

The same result uses the init() method instead of the x-init directive.

<!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="{
        message: 'Alpine Rocks',
        init() { $nextTick(() => console.log($el.value)) }
      }"
      x-model="message"
    />
  </body>
</html>

Line 10

<input
  x-data="{
    message: 'Alpine Rocks',
    init() { $nextTick(() => console.log($el.value)) }
  }"
  x-model="message"
/>
  • init() : if the x-data Object of a component contains an init() method, it will be called automatically without x-init directive

Conclusion

  • init() may be useful in some situation

Reference

Alpine, x-init