In this episode, we're diving into making our lists sortable using the popular sortable.js
package, but with an Alpine.js twist! We'll walk you through how to manually bundle Alpine into Livewire instead of using the default setup. This approach is important because it lets us register custom Alpine plugins easily.
First up, we adjust the build to import Alpine and Livewire directly in our main JavaScript file, and set up the app so that we can call Alpine.plugin(...)
to add any plugins we want. Then, we jump straight into creating our own sortable.js
Alpine plugin. To make sure it's working, we log out a quick test in the console, and voilà – our plugin is active!
Next, we install the actual sortable.js
library, import it into our new plugin file, and show you how to use Alpine's API to register a custom directive (which we'll call x-sortable
). This directive gets attached to your list in the Blade file—just add x-sortable
to your component, and you're good to go.
We wire things up so that you can drag and drop to reorder items in your list, and introduce a data attribute (x-sortable-item
) to uniquely identify each list item by its ID. This prepares everything for keeping your database in sync with the updated order later.
By the end, you've got a sortable list in Livewire using Alpine and sortable.js
, with unique IDs in place. Next episode, we'll handle dispatching an event so Livewire can actually save those new orders. But for now, you've learned the full setup for integrating a third-party drag-and-drop library with Alpine in a Livewire project. Pretty sweet!