"Implementing drag and drop functionality in Vue.js without the need for a

Exploring html 5 drag and drop functionality using vue js has been a challenging experience for me.

After following the w3schools tutorial on drag and drop, I managed to get it working in a basic html file but faced difficulties when implementing it in my vue project.

If you're interested, here is the code and link to the tutorial I used: w3schools - drag: https://www.w3schools.com/jsref/event_ondrag.asp The error message I encountered reads as follows: Uncaught Reference Error: allowDrop is not defined

Despite defining all necessary methods within the method scope of vue js, the issue persisted.

Answer №1

Make sure to utilize the Vue event rather than the HTML event by using v-on:drop instead of drop, for instance.

Check out how you can implement the provided example link with Vue:

<html>
      <head>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <style>
        .droptarget {
      float: left; 
      width: 100px; 
      height: 35px;
      margin: 15px;
      padding: 10px;
      border: 1px solid #aaaaaa;
    }
    </style>
        </style>
      </head>
      <body>
        <div id="app">
          <p>Drag the p element back and forth between the two rectangles:</p>
          <div
            class="droptarget"
            v-on:drop="drop"
            v-on:dragover="allowDrop"
          >
            <p
            v-on:dragstart="dragStart"
              v-on:drag="dragging"
              draggable="true"
              id="dragtarget"
            >
              Drag me!
            </p>
          </div>
    
          <div
            class="droptarget"
            v-on:drop="drop"
            v-on:dragover="allowDrop"
          ></div>
    
          <p style="clear:both;">
            <strong>Note:</strong> drag events are not supported in Internet 
            Explorer 8 and earlier versions or Safari 5.1 and earlier versions.
          </p>
    
          <p id="demo"></p>
        </div>
        <script>
          var app = new Vue({
            el: "#app",
           
            methods: {
              dragStart:function(event)  {
                event.dataTransfer.setData("Text", event.target.id);
              },
              dragging:function(event) {
                document.getElementById("demo").innerHTML =
                  "The p element is being dragged";
              },
              allowDrop:function(event) {
                event.preventDefault();
              },
              drop:function(event) {
                event.preventDefault();
                var data = event.dataTransfer.getData("Text");
                event.target.appendChild(document.getElementById(data));
                document.getElementById("demo").innerHTML =
                  "The p element was dropped";
              }
    
            }
          });
        </script>
      </body>
    </html>

Answer №2

To prevent the default behavior of web browsers, you can utilize @dragover.prevent along with @drop.stop.prevent.

If you desire more in-depth information on event handling, feel free to refer to the documentation: VueJS Event Handling Documentation

Below is a sample implementation of a basic drag & drop feature:

new Vue({
  el: "#app",
  methods: {
    // This method will be triggered by '@drop.stop.prevent' when a file is dropped over our app
    onDrop(event) {
      const file = event.dataTransfer.files[0];

      // Perform actions with the dropped file
      console.log(file)
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

p {
  text-align: center
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>

<div id="app" @dragover.prevent @drop.stop.prevent="onDrop">
  <p>Drag & Drop</p>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the Power of Observables in Angular 2: Focusing on Targeting an Array Nested Within

I encountered a situation where I was successfully looping through objects in an array within my Angular 2 application using observables. In the client service file, my code looked like this: getByCategory(category: string) { const q = encodeURICompon ...

Having trouble with the ng-class syntax?

I've been diving into the world of Angular.js and came across this code snippet: <button ng-class="{'btn pull-left', duplicatesInList === true ? 'btn-warning': 'btn-success'}" id="saveScoreButton" type="button" ng-c ...

Is it feasible for JSON.stringify to maintain functions in its serialization?

Consider this item: x = { "key1": "xxx", "key2": function(){return this.key1} } Suppose I execute the following code: y = JSON.parse( JSON.stringify(x) ); After running the above code, y will contain { "key1": "xxx" }. Is there a way to include funct ...

Website API: decouple backend and frontend functionality through an API

I am currently working on the development of a website and an app created through Cordova. The app will essentially mirror the functionalities of the website. The website is already established and heavily relies on JavaScript, with potential considerati ...

Is there a way to convert the text within a div from Spanish to English using angular.js?

I am working with a div element that receives dynamic text content from a web service in Spanish. I need to translate this content into English. I have looked into translation libraries, but they seem more suited for individual words rather than entire dyn ...

Is it possible for me to include a static HTML/Javascript/jQuery file in WordPress?

My extensive HTML file contains Javascript, jQuery, c3.js, style.css, and normalize.css. I am wondering if I can include this file as a static HTML page within Wordpress. Say, for instance, the file is called calculator.html, and I want it to be accessib ...

Having trouble accessing the value of an object within a nested array object

Looking for a way to extract the object value from a nested array object using JavaScript? If the sourcecountry matches the country in the object, it should return the corresponding payment service. Here is what I have attempted: function getValue(source ...

Utilizing jQuery to implement a CSS style with a fading effect, such as FadeIn()

I have a jQuery script that applies a CSS style to an HTML table row when the user clicks on a row link: $(this).closest('tr').css("background-color", "silver"); Is there a way to soften this color change effect, such as by gradually fading in ...

Displaying or concealing an input field in vue.js depending on the selection of a radio button

I am currently working on customizing a pre-built form in Vue.js, where certain inputs are displayed or hidden based on the selection of two radio buttons: <b-form-group label-class="ssrv-form-control"> <div class="ssrv-5"& ...

Updating input value in React on change event

This is the code for my SearchForm.js, where the function handleKeywordsChange is responsible for managing changes in the input field for keywords. import React from 'react'; import ReactDOM from 'react-dom'; class SearchForm extends ...

AngularJS Setting Default Values in HTML Pages

My goal is to set the default value for a dropdown in an Angular HTML Page. The page uses tabs, and I want the default value to load when a specific tab is clicked. <div class="col-md-9" ng-cloak ng-controller="ServiceTypeController"> <md-conten ...

Exploring the world of promise testing with Jasmine Node for Javascript

I am exploring promises testing with jasmine node. Despite my test running, it indicates that there are no assertions. I have included my code below - can anyone spot the issue? The 'then' part of the code is functioning correctly, as evidenced b ...

When using window.open in Chrome on a dual screen setup, the browser will bring the new window back to the

When using the API window.open to open a new window with a specified left position in a dual screen setup (screen1 and screen2), Chrome behaves differently than IE and FF. In Chrome, if the invoking screen is on the right monitor, the left position always ...

Dealing with authorization errors in Python using Graphene

My current environment setup is as follows: Frontend @vue/cli 4.1.2 vue-apollo 3.0.2 Backend python 3.8 django 3.0.2 graphene-django 2.8.0 django-graphql-jwt 0.3.0 I am struggling to handle authentication errors when the token expires. For instanc ...

Adjust the height of each card dynamically based on the tallest card in the row

I am working on a row that looks like this: <div class="row"> <div class="col"> <div class="card"> <div class="card-body"> <h3 class="card-title ...

Incorporating Numerous Location Pointers in Angular-google-maps

I've been struggling to show multiple map markers in my Angular project. I have a service called retsAPI that queries a local MLS database for home listings, and I'm attempting to display these items on a Google map. Below is my controller code. ...

Exploring the Lifecycle Methods in ReactJS / Issue Resurfacing in the Code Snippet

I recently started learning ReactJS and discovered the concept of lifecycles. However, I have a question about how componentDidUpdate() works and why it behaves in a certain way. To illustrate this, I am sharing a simple code snippet below that calculates ...

Failed to send JSON data to WebMethod

I am encountering difficulties while attempting to send JSON to a WebMethod. I have provided the method I am using below. If there is a more efficient approach, please advise me. My goal is to store the JSON object in a database. JavaScript function TEST ...

The jQuery .hasClass() function does not work properly with SVG elements

I am working with a group of SVG elements that are assigned the classes node and link. My goal is to determine whether an element contains either the node or link class when hovering over any of the SVG components. However, I am encountering an issue where ...

Extract the content of a textbox within an iframe located in the parent window

Is it possible to retrieve the value of a text box in an iframe from the parent page upon clicking a button? Below is an example code snippet showcasing the situation: <div> <iframe src="test.html" > <input type=text id="parent_text"> & ...