-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path08-loops.html
100 lines (85 loc) · 2.97 KB
/
08-loops.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<!doctype html>
<html lang="en">
<head>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!-- Easy Installation: https://alpinejs.dev/essentials/installation -->
<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
<title>Alpine.js : Declare & React</title>
</head>
<body>
<!--
Looping over arrays, lists, objects
https://alpinejs.dev/directives/for
In order for alpine to track the dom, use the <template> tag for the repeatable UI
-->
<!-- Iterate over a range -->
<div x-data>
<ul>
<template x-for="i in 10">
<li x-text="i"></li>
</template>
</ul>
</div>
<hr class="my-5">
<!-- Simple array representation -->
<div
class="vstack gap-3"
x-data="{ people : [ 'luis', 'brad', 'grant', 'michael' ] }"
>
<template x-for="person in people">
<div class="border p-1 bg-light" x-text="person"></div>
</template>
</div>
<hr class="my-5">
<!-- Let's add an index -->
<div
class="vstack gap-3"
x-data="{ people : [ 'luis', 'brad', 'grant', 'michael' ] }"
>
<template x-for="person, index in people">
<div class="border p-1 bg-light" x-text="`${index+1}. ${person}`"></div>
</template>
</div>
<hr class="my-5">
<!-- Let's add records -->
<div
class="vstack gap-3"
x-data="{
newPerson : '',
people : [
{ id : 1, name : 'Luis' },
{ id : 2, name : 'Brad' },
{ id : 3, name : 'Michael' },
{ id : 4, name : 'Grant' },
],
init(){
// go fetch some records!!
},
add(){
// Call Server
this.people.push( {
id : this.people[ this.people.length - 1 ].id + 1,
name : this.newPerson
} );
this.newPerson = ''
},
remove( index ){
// Call Server
this.people.splice( index, 1 );
}
}"
>
<input type="text" x-model="newPerson" placeholder="Add new person">
<button @click="add" :disabled="newPerson.length === 0">Add</button>
<!-- key is the unique reference for the row so the dom can follow -->
<template x-for="person, index in people" :key="person.id">
<div class="border p-1 bg-light">
<span x-text="index+1"></span>.
<span x-text="person.name"></span>
(<span x-text="person.id"></span>)
<button class="float-end" @click="remove( index )">X</button>
</div>
</template>
</div>
</body>
</html>