v0.6.22

Loop Rendering

Last updated


This page explains how :for expands arrays and objects, and which variables are reachable inside a loop.

Arrays


  1. <ul id="app">
  2. <li :for="item in items">{{ item }}</li>
  3. <li :for="(item, index) in items">{{ index }}. {{ item }}</li>
  4. </ul>
  5. <script>
  6. const app = new QUI({ id: "app", data: { items: ["A", "B", "C"] } });
  7. </script>
Live preview · @pardnchiu/quickui@0.6.22

SyntaxVariables
item in listitem is the element
(item, index) in listAdds a zero-based index

Objects


  1. <ul id="app">
  2. <li :for="(key, value) in user">{{ key }}: {{ value }}</li>
  3. </ul>
  4. <script>
  5. const app = new QUI({ id: "app", data: { user: { name: "Pardn", role: "Developer" } } });
  6. </script>
Live preview · @pardnchiu/quickui@0.6.22

The first variable is the key and the second is the value; with a single variable you only get the key.

Scope


ReachableDescription
Loop variablesitem, index (or key, value)
Source collectionRead from root data under the same name, for example items
Root dataLooked up in app.data when the loop scope has no match
Outer loop variablesNot reachable; the inner body of a nested loop only sees its own variables and root data

  1. <div id="app">
  2. <div :for="group in groups">
  3. <h3>{{ group.name }}</h3>
  4. <p :for="member in group.members">{{ member }}</p>
  5. </div>
  6. </div>
  7. <script>
  8. const app = new QUI({
  9. id: "app",
  10. data: {
  11. groups: [
  12. { name: "Frontend", members: ["Pardn", "Chiu"] },
  13. { name: "Backend", members: ["Ching-Wei"] },
  14. ],
  15. },
  16. });
  17. </script>
Live preview · @pardnchiu/quickui@0.6.22

The inner source path group.members may use the outer variable, but {{ group.name }} inside the inner element is not replaced.
中文