When you use VueDraggable to visually sort the items, you often want to make sure that you keep an order or position field in sync with the new order of items in your data array. VueDraggable makes reordering easy but it doesn’t update custom fields on the items on its own.
Why You Need to Update the order Field
VueDraggable reorders the array when you drag and drop, but if your items have an explicit order or position field that you use in your backend or database you will need to update it manually. Otherwise, your visual order and the order you have saved can become mismatched.
How to Resolve It with @end Event
VueDraggable will send out events when sorting is done. Use the @end event to loop through your items and update each item’s order field to match its new index.
<template> <draggable v-model="items" @end="updateOrder"> <template #item="{ element }">
<div>{{ element.name }} (Order: {{ element.order }})</div>
</template>
</draggable>
</template>
<script setup>
import { ref } from 'vue'
import draggable from 'vuedraggable'
const items = ref([
{ id: 1, name: 'Item 1', order: 1 },
{ id: 2, name: 'Item 2', order: 2 },
{ id: 3, name: 'Item 3', order: 3 }
])
function updateOrder() {
items.value.forEach((item, index) => {
item.order = index + 1
})
}
</script>
Also Read: The Vue JS Best Practices In Detail
How It Works
- v-model="items" binds your data to VueDraggable.
- @end="updateOrder" runs updateOrder when sorting finishes.
- updateOrder loops through your array and sets item.order to index + 1.
Key Takeaway
VueDraggable makes reordering lists easy, but it’s your job to update your custom order field to match the new position. Use the @end event to keep your data and backend consistent with what the user sees.
Related Resources