AlpineJS

Robert Rees - Sep 10 '22 - - Dev Community

Recently I needed to knock up some dynamic content on a website at short notice. I've previously used VueJS for quick and dirty projects like this and enjoyed it as a modern take on KnockoutJS. So I loaded up the Vue homepage started following the Get Started guide and quickly got into a humongous non-functioning mess.

Vue is still a lightweight, clever framework and if your project isn't full on enterprise React then it is a good choice. But what it clearly isn't any more is a drop a script on a page and get coding solution.

With a bit of a deadline (due to a mixture of procrastination and confidence that Vue would work) I needed something quick. I have also used Hyperapp in the past but that looks like a dead project right now (although arguably it has all the functionality you need so why keep developing it?).

So having briefly looked at AlpineJS in the past I decided to give it a spin and luckily Alpine was the hero I needed.

You just have to include a script and then for simple dynamic behaviour event handlers are added according to your usage and you can put simple script commands inline within the attribute value.

For my need I want to render a view based on a model and regenerate that model based on user interactions (a button click).

This is a bit more involved but still only really involves two directives: data and on.

The data directive sets a scope for access to the data (and this bit is a little bit weird because really the model is quite abstract for me and not linked to the DOM state like a lot of the examples) and also initialises it. I created a generator function that can be called to provide an initial state and then on the subsequent events create new state. The rest of the implementation is simply showing the right values from the model in the right places in the DOM.

I also ended up using the Alpine.data method to try and encapsulate my whole implementation as a component, even though I actually ended up only using it once on the page.

So after a few hours of panic coding and reading and implementing from the docs I had my page up and running and a new lightweight framework that I want to try pushing on a bit more to see how much it can do before you want something more heavyweight.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player