The issue with the current code is that it doesn't apply any styles to the item being dragged. To fix that, we can set a style based on draggingIndex value and apply it to the item being dragged to give it an effect to indicate it's being picked up.
Here's the updated code:
<template>
<transition-group name="list-item" tag="div" class="list-container">
<div
v-for="(item, index) in list"
:key="item.id"
:class="['list-item', { 'is-dragging': draggingIndex === index }]"
@mousedown="startDrag(index, $event)"
@touchstart="startDrag(index, $event)"
>
{{ item.value }}
</div>
</transition-group>
</template>
<script>
import {reactive, computed} from 'vue';
export default {
setup() {
const state = reactive({
list: [
{id: 1, value: 'Item 1'},
{id: 2, value: 'Item 2'},
{id: 3, value: 'Item 3'},
{id: 4, value: 'Item 4'},
],
draggingIndex: null,
initialMouseY: 0,
});
const list = computed(() => state.list);
const draggingIndex = computed(() => state.draggingIndex);
const startDrag = (index, event) => {
state.draggingIndex = index;
state.initialMouseY = event ? (event.pageY || event.touches[0].pageY) : 0;
document.addEventListener('mousemove', doDrag);
document.addEventListener('touchmove', doDrag);
document.addEventListener('mouseup', stopDrag);
document.addEventListener('touchend', stopDrag);
};
const doDrag = (event) => {
if (state.draggingIndex === null) return;
const mouseY = event ? (event.pageY || event.touches[0].pageY) : 0;
const deltaY = mouseY - state.initialMouseY;
const targetIndex = state.list.findIndex((item, index) => {
const rect = event ? event.target.getBoundingClientRect() : null;
return index !== state.draggingIndex && rect && rect.top + rect.height / 2 > mouseY;
});
if (targetIndex !== -1) {
const tmpItem = state.list[state.draggingIndex];
state.list.splice(state.draggingIndex, 1);
state.list.splice(targetIndex, 0, tmpItem);
state.draggingIndex = targetIndex;
state.initialMouseY = mouseY;
}
};
const stopDrag = () => {
if (state.draggingIndex === null) return;
document.removeEventListener('mousemove', doDrag);
document.removeEventListener('touchmove', doDrag);
document.removeEventListener('mouseup', stopDrag);
document.removeEventListener('touchend', stopDrag);
state.draggingIndex = null;
};
return {
list,
draggingIndex,
startDrag,
};
},
};
</script>
<style scoped>
.list-container {
display: flex;
flex-direction: column;
}
.list-item {
padding: 1rem;
background-color: #352828;
cursor: grab;
user-select: none;
transition: transform 300ms, box-shadow 300ms, z-index 0ms;
}
.list-item-move {
transition: transform 300ms;
}
.list-item.is-dragging {
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
z-index: 1;
}
</style>
In the updated code, I've added a new class is-dragging and applied it to the item being dragged. A box-shadow style is applied, and the z-index is set to 1 to lift the item being dragged above other items. Also, the draggingIndex now returns a computed property to use in the template.