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
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
: defineusers
as Empty Arrayx-init
: initialize data by expression
Conclusion
x-init
let us initialize data by JavaScript