點燈坊

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

Using x-for with Index

Sam Xiao's Avatar 2022-01-27

x-for also support index like Vue’s v-for.

Version

Alpine 3.9

x-for

index000

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

Reference

Alpine, x-for