Building a Drag and Drop Interface with Vue.js
Overview: In this blog post, we'll walk through the process of building a drag-and-drop interface with Vue.js. We'll cover the basics of defining the components for our application, implementing the functionality to drag and drop items between lists, and using Vuex to manage the state of the application.
Code Snippet:
html
<template>
<div>
<h2>Tasks</h2>
<div class="task-list">
<div
class="task"
v-for="(task, index) in tasks"
:key="task.id"
:draggable="true"
@dragstart="handleDragStart(index)"
@dragend="handleDragEnd"
>
{{ task.name }}
</div>
</div>
<h2>In Progress</h2>
<div
class="task-list"
@dragover.prevent
@drop="handleDrop('inProgress')"
>
<div
class="task"
v-for="(task, index) in inProgressTasks"
:key="task.id"
:draggable="true"
@dragstart="handleDragStart(index, 'inProgress')"
@dragend="handleDragEnd"
>
{{ task.name }}
</div>
</div>
<h2>Completed</h2>
<div
class="task-list"
@dragover.prevent
@drop="handleDrop('completed')"
>
<div
class="task"
v-for="(task, index) in completedTasks"
:key="task.id"
:draggable="true"
@dragstart="handleDragStart(index, 'completed')"
@dragend="handleDragEnd"
>
{{ task.name }}
</div>
</div>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
export default {
computed: {
...mapState(['tasks', 'inProgressTasks', 'completedTasks']),
},
methods: {
...mapMutations(['MOVE_TASK']),
handleDragStart(index, type = 'tasks') {
this.draggedTask = {
index,
type,
};
},
handleDragEnd() {
this.draggedTask = null;
},
handleDrop(type) {
if (this.draggedTask.type !== type) {
this.MOVE_TASK({
task: this[this.draggedTask.type][this.draggedTask.index],
to: type,
});
}
},
},
};
</script>
No comments:
Post a Comment