-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path09-computed-properties.html
81 lines (69 loc) · 2.46 KB
/
09-computed-properties.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
<!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>
<!-- Simple Example -->
<div x-data="{
message : '',
get shoutGreeting(){
return `${this.message.toUpperCase()}`
}
}">
<input type="text" x-model="message">
<span x-text="shoutGreeting"></span>
</div>
<hr class="my-5">
<!-- Computed Array -->
<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' }
],
get sortedPeople(){
return this.people.sort( (a,b) => a.name > b.name );
},
init(){
// go fetch some records!!
},
get maxId(){
let sortedById = this.people.sort( (a,b) => a.id - b.id );
return sortedById[ sortedById.length-1 ].id;
},
add(){
// Call Server
this.people.push( {
id : this.maxId + 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 sortedPeople" :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>