Lifetime access is $100 off. Available for a limited time.Join here →

Computed properties in Alpine.js

May 19th, 2020

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. Thanks Ryan!

Thanks for reading! If you found this article helpful, you might enjoy our practical screencasts too.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first to leave a comment.

Tagged under