x-for
also support index like Vue’s v-for
.
Version
Alpine 3.9
x-for
The index is created by x-for
.
<!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="{ colors: ['Red', 'Green', 'Blue']}">
<ul>
<template x-for="(x, i) in colors" :key="i">
<li x-text="`${i} : ${x}`" />
</template>
</ul>
</body>
</html>
Line 9
<body x-data="{ colors: ['Red', 'Green', 'Blue']}">
<ul>
<template x-for="(x, i) in colors" :key="i">
<li x-text="`${i} : ${x}`" />
</template>
</ul>
</body>
We can also bind index to key
.
Conclusion
- We can use the index created by
x-for
to bind to:key