DEV Community

Cover image for Flash Code#1 Drag&Drop Component Using Vue.js

Posted on

Flash Code#1 Drag&Drop Component Using Vue.js

In this short article I will show you how to create a drag and drop component using Vue.js and Tailwindcss.


link: Flash Code

Drag Drop

Let's start with the UI:

We will put a single div with a few tailwind classes:

What those css classes do:
  • bg-gray-200, rounded-lg, border-2, border-dashed, and border-gray-500: These are Tailwindcss classes. They are pretty self explanatory but if you want more infos you can checkout Tailwind's docs.
  • dropzone: Sets the width to 400px and the height to 500px.

And that's what we get:
Drop Area

Now let's add some text inside. We can do that by simply adding another div inside the first one.

All the css classes are from Tailwindcss except for dropzone-child-elements, this class prevents the user from interacting with the content inside the dropzone and it contains only one rule:
pointer-events: none;

This is what it looks like:
Text Inside Drop Area

It's time to make it do something (the logic):

1-Change the border color when dragging a file:
First, let's make the dropzone interactive by changing the border color when a file is dragged in. We will use the dragenter and dragleave events to detect if a file is hovering the drop area. We will use a variable named fileOverDropArea to control the border color.

Let me explain how it works:
This code sets fileOverDropArea to true or false when a file is entering or leaving the drop down area.
.prevent cancels the default actions when those events are fired.

Thanks to Vue we can bind the class attribute to add some classes only if certain conditions are met. In this case we are setting the border color to a dark gray if fileOverDropArea is false and to red if it is true.

2- Handling the file upload:
Now that we got the hover animation to work, let's handle the file uploading part.
This is the easiest part actually, all we have to do is to listen for another event called drop and then call a method when the event is fired.
To do that we will add this line of code to the dropzone div:


This is the code of the dropFile method:

Complete Component Code:

A quick word about this series:

Flash Code is a series of posts showing you how to build various components using Vuejs. This was the first post, and many will come out in the following weeks.
I would love to hear your thoughts on this first post (this is actually my first blog post ever).
Thanks for reading.

Top comments (0)