點燈坊

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

Using x-init to Initialize x-data

Sam Xiao's Avatar 2022-02-11

Not only can we define data in x-data directly, but also we can initialize the data in x-init.

Version

Alpine 3.8

x-init

overview000

Data is not defined in x-data, but in x-init.

<!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="{ users: [] }" x-init="users = ['Sam', 'Tom', 'Ray']">
    <ul>
      <template x-for="x in users">
        <li x-text="x" />
      </template>
    </ul>
  </body>
</html>

Line 9

<body x-data="{ users: [] }" x-init="users = ['Sam', 'Tom', 'Ray']">
  <ul>
    <template x-for="x in users">
      <li x-text="x" />
    </template>
  </ul>
</body>
  • x-data : define users as Empty Array
  • x-init : initialize data by expression

Conclusion

  • x-init let us initialize data by JavaScript

Reference

Alpine, x-init