JavaScript Getter is handy when the sole purpose of a method is to return data based on another state. Think of them like Computed Property in Vue.
Version
Alpine 3.8
TailwindCSS
Use Getter directly in HTML just like TailwindCSS.
<!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="{
name: 'World',
get greeting() {
return `Hello ${ this.name }`
}}"
>
<span x-text="greeting" />
</body>
</html>
Line 9
<body
x-data="{
name: 'World',
get greeting() {
return `Hello ${ this.name }`
}}"
>
get greeting()
: use Getter to for computed propertyx-text
: bind to Getter directly
Vue
- It may be too verbose to use Getter in HTML
- We can use Getter in JavaScript just like Vue
<!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>
<script>
let helloWorld = {
name: "World",
get greeting() {
return `Hello ${this.name}`;
},
};
</script>
</head>
<body x-data="helloWorld">
<span x-text="greeting" />
</body>
</html>
Line 9
let helloWorld = {
name: "World",
get greeting() {
return `Hello ${this.name}`;
},
};
Implement getter on helloWorld
Object. It’s more readable in JavaScript.
Line 17
<body x-data="helloWorld">
<span x-text="greeting" />
</body>
x-data
: bindhelloWorld
Object tox-data
directivex-text
: bind to getter directly
Svelte
We can also use function to implement Getter just like Svelte.
<!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>
<script>
let greeting = (x) => `Hello ${x.name}`;
</script>
</head>
<body x-data="{ name: 'World' }">
<span x-text="greeting($data)"></span>
</body>
</html>
Line 12
<body x-data="{ name: 'World' }">
<span x-text="greeting($data)"></span>
</body>
- Define data in
x-data
directive - Pass
$data
togreeting
.$data
is a proxy of data inx-data
Line 9
let greeting = (x) => `Hello ${x.name}`;
- Since
$data
is a proxy, we can usex.name
to accessname
state - We don’t have to use
this
to access data so that we can use arrow function instead of function expression
Conclusion
- Alpine’s Getter is not cached like Vue’s computed property