點燈坊

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

Using x-for with Key

Sam Xiao's Avatar 2022-01-27

We can also bind a unique value to :key just like Vue.

Version

Alpine 3.9

x-for

key000

If data will be added, removed, or re-ordered, we have to bind key with 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: [
        { id: 1, label: 'Red'},
        { id: 2, label: 'Green'},
        { id: 3, label: 'Blue'}
      ]}"
  >
    <ul>
      <template x-for="x in colors" :key="x.id">
        <li x-text="x.label" />
      </template>
    </ul>
  </body>
</html>

Line 9

<body
  x-data="{
    colors: [
      { id: 1, label: 'Red'},
      { id: 2, label: 'Green'},
      { id: 3, label: 'Blue'}
    ]}"
>
  <ul>
    <template x-for="x in colors" :key="x.id">
      <li x-text="x.label" />
    </template>
  </ul>
</body>

Bind id to key.

Conclusion

  • We can use the unique value provided by data to bind to :key

Reference

Alpine, x-for