May 19th, 2020 by Alex Garrett-Smith

Computed properties in Alpine.js

If you're using Alpine.js and also use a framework like Vue.js, you're probably missing computed properties right now.

Up until recently, I'd been achieving things I wanted computed using functions, and while it worked, it didn't feel right.

<div x-data="setup()">
<span x-text="shoutyGreeting()"></span>
</div>
 
<script>
function setup () {
return {
greeting: 'Hello there',
 
shoutyGreeting () {
return `${this.greeting.toUpperCase()}!`
}
}
}
</script>

Turns out there's a really simple solution to this... use a JavaScript getter. A getter in a JavaScript class or object binds a property to a function which allows it to be magically invoked when that property is accessed.

So, we end up with this.

<div x-data="setup()">
<span x-text="shoutyGreeting"></span>
</div>
 
<script>
function setup () {
return {
greeting: 'Hello there',
 
get shoutyGreeting () {
return `${this.greeting.toUpperCase()}!`
}
}
}
</script>

So, although Alpine.js doesn't actually support the concept of computed properties, this feels much nicer.

I picked this tip up from An Alternative Approach to Computed Properties in Alpine.js on Ryan Chandler's blog. Cheers Ryan.