Use Shopify/draggable with Alpine.js x-for directive

Viewed 1228

I'm trying to make the sortable plugin from Shopify working with Alpine.js but when I drag and drop the items, it generate the error in the console

"Alpine Error: 'ReferenceError: framework is not defined'
Expression: 'framework'
Element: "<li x-text="framework" tabindex="0" style="" class="draggable-source--is-dragging">springs</li>

Here's a reproducible example

https://codepen.io/cbaconnier/pen/bGgxyWE?editors=1011

<html>
<head>
</head>
<body>
<div x-data="{frameworks: ['laravel', 'rails', 'django', 'springs']}">
  
<ul> 
  <template x-for="framework in frameworks" :key="framework">
    <li x-text="framework"></li>
  </template>
</ul>
  
</div>

<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.8.2/dist/alpine.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@shopify/draggable@1.0.0-beta.12/lib/sortable.js"></script>
<script>
  const sortable = new Sortable.default(document.querySelectorAll('ul'), {
      draggable: 'li'
    });
</script>
</body>
</html>

I know there's some homemade dragable/sortable that have been done with Alpine.js but since I'm already using it with Livewire on this project and some other, it would be nice to also make it works.

1 Answers

Even though I would like to keep Shopify/draggable I have resigned to use SortableJS/Sortable that seems to works quit well.

<html>
<head>
</head>
<body>
<div 
    x-data="{frameworks: ['laravel', 'rails', 'django', 'springs']}"
    x-init="Sortable.create($refs.items)"
>
  
<ul x-ref="items"> 
  <template x-for="framework in frameworks" :key="framework">
    <li x-text="framework"></li>
  </template>
</ul>
  
</div>

<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.8.2/dist/alpine.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.13.0/Sortable.min.js"></script>
</body>
</html>

Related