having trouble retrieving the DOM element in Vue.js

I'm currently working on developing a drag and drop component, but I've encountered an issue with selecting the div using getElementById. When I try to do so, I receive an error message stating:

Uncaught TypeError: Cannot read property 'addEventListener' of null
.

Additionally, the console log is showing null instead of the actual div element.

<template>
    <div class="highlight" id="dragZone">
      <input
        v-model="inputText"
        placeholder="Write something..."
      />
    </div>
</template>
<script>
import $auth from '@/services/auth';
import $utils from '@/services/utils';

const dropArea = document.getElementById('dragZone');
console.log(dropArea);

// Prevent default drag behaviors
function preventDefault(e) {
  e.preventDefault();
  e.stopPropagation();
}

dropArea.addEventListener('dragenter', preventDefault, false);
dropArea.addEventListener('dragleave', preventDefault, false);
dropArea.addEventListener('dragover', preventDefault, false);
dropArea.addEventListener('drop', preventDefault, false);

// Handle dropped files
async function handleDrop(e) {
  const dt = e.dataTransfer;
  const files = dt.files;
  this.uploadingFile = await $utils.uploadFile(files, credentials);
}

dropArea.addEventListener('drop', handleDrop, false);

export default {
  props: {
    links: {
      type: Object,
    },
  },
  data(){
   return{
      uploadingFile: null
  }
}

</script>

Answer №1

When working with Vuejs, it's important to place your function within the component's method object.

Additionally, any logic that should be executed when the component is mounted should be placed inside the mounted object.

Visit this link for more information on Vue.js

import $auth from "@/services/auth";
import $utils from "@/services/utils";

export default {
  props: {
    links: {
      type: Object,
    },
  },
  data() {
    return {
      uploadingFile: null,
    };
  },
  methods: {
    async handleDrop(e) {
      const dt = e.dataTransfer;
      const files = dt.files;
      this.uploadingFile = await $utils.uploadFile(files, credentials);
    },
    preventDefault(e) {
      e.preventDefault();
      e.stopPropagation();
    },
  },
  mounted() {
    // Place logic that needs to run when the component is mounted
    const dropArea = document.getElementById("dragZone");
    console.log(dropArea);

    // Prevent default drag behaviors

    dropArea.addEventListener("dragenter", this.preventDefault, false);
    dropArea.addEventListener("dragleave", this.preventDefault, false);
    dropArea.addEventListener("dragover", this.preventDefault, false);
    dropArea.addEventListener("drop", this.preventDefault, false);

    // Handle dropped files

    dropArea.addEventListener("drop", this.handleDrop, false);
  },
};

It's recommended to use ref if you need to access the DOM element directly. Learn more here

For a deeper understanding of Vuejs functionality, refer to the official documentation at: https://vuejs.org/

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

New in the world of JavaScript: A method that replicates the functionality of jQuery's

Take a look at this JSFiddle example: https://jsfiddle.net/1a6j4es1/1/ $('table').on('click', 'td', function() { $(this).css('background', 'green'); }); How can you rewrite this code using plain JavaS ...

Transferring a JavaScript variable to C# to execute an SQL SELECT query, then sending the returned result back to JavaScript

I am facing an issue while trying to execute code in my Code Behind to query my SQL Server using a JavaScript variable and then return the result as an Integer back to my Javascript. My approach involves running some Javascript code initially to obtain a ...

Encountering an error during the installation process of Vue Native using the Vue

I recently created a project called helloworld, following the instructions at However, I encountered an error while trying to start my first application: Unable to resolve "../../App" from "node_modules/expo/AppEntry.js" Here is information about my env ...

Activate the text area message by clicking on the href link

I am currently working on customizing the intercom plugin for a WordPress site. My goal is to have a message triggered when a user clicks on a hyperlink, essentially simulating the enter key press in a textarea. Here is the code snippet that I am using: ...

What is the best way to submit a Redux Form only if there have been changes made to any of the fields

I'm currently using Redux Form version 7.1.2, and I have a form that submits data when the user clicks the submit button. In the function assigned to handle the submission, I perform an action. However, I only want this action to be executed if there ...

Explore the steps for setting up automatic reconnection in socket.io

When establishing a socket.io connection, I use the following code: var socket = new io.connect('http://localhost:8181', { 'reconnect': true, 'reconnection delay': 500, 'max reconnection attempts': 50 }) ...

NodeAutoComplete: Enhanced Autocompletion for Node.js

I am attempting to utilize autocompletion of a JavaScript file with Node.js and Tern. However, the documentation for Ternjs is incredibly lacking. const tern = require("tern"); const ternServer = new tern.Server({}); const requestDetails = { "qu ...

Having trouble with Semantic UI Modal onShow / onVisible functionality?

Seeking assistance with resizing an embedded google map in a Semantic UI modal after it is shown. After numerous attempts, I have narrowed down the issue to receiving callbacks when the modal becomes visible. Unfortunately, the onShow or onVisible functio ...

In Node JS, the variable ID is unable to be accessed outside of the Mongoose

When working with a Mongoose query, I encountered an error where I am trying to assign two different values to the same variable based on the query result. However, I keep getting this error: events.js:187 throw er; // Unhandled 'error' ev ...

Transferring data to server using AngularJS and Java Servlet Technology

I am currently facing a challenge in developing a webpage that enables file uploads from a local machine to a server using AngularJS and Java Servlet. My approach involves sending data to the server using $http.post and attempting to read the file data usi ...

How to Transfer a Props Value to an External Function in Vue 3

I'm currently working on a page that displays user details and need to also show the invoices associated with that user. <template> <div> <div> // Child component one ..... </div> <div ...

Utilizing conditional statements like if/else and for loops within a switch statement in JavaScript allows for

I am currently developing a request portal that involves dynamic checkboxes, labels, and textboxes that are dependent on an option list. As a beginner in javascript, I am facing challenges with creating conditional statements. I have managed to make progr ...

Tips for detecting when a user unexpectedly leaves an ASP.Net page

Is there a way to notify users when they are leaving my ASP.Net page without triggering a warning when they click the save button? I've been reading several articles on this topic, but being new to it all has left me confused. The suggested solution ...

Gulp does not generate any new folders

Currently, my workspace is located in a directory named "Super gulp" with other directories that contain my files. The issue I'm facing is related to converting my .pug files into HTML files and placing them in the "goal" directory. However, when I tr ...

Utilize AngularJS to inject a service into a module without assigning it to a variable, enabling easier minification

Currently, I am attempting to decrease the size of my AngularJS JavaScript code (using SquishIt). Within my module, there is a service injected as a function argument, as shown below. var myapp = angular.module('myapp', ['ngSanitize'] ...

React Hook Form – Difficulties with error handling when utilizing multiple forms simultaneously in react hook form version 7.5.2

Previously, in the earlier versions of react hook form, multiple forms could function if another form object was created using the following code: const { register: register2, handleSubmit: handleSubmit2, errors: errors2 } = useForm() H ...

JavaScript SQL results in either a string or an object after executing a

I am facing an issue with the following query: sql = client.query("SELECT * FROM monitormaterialsept", function (err, result, fields) { if (err) throw err; console.log(result); }) I am unsure of what the output of the sql variable is. Is there a ...

Guide to handling HTTP request parsing in Express/NodeJs when the content type is missing, by setting a default content type

Is it possible to retrieve POST data in an express request when the bodyParser does not work? var server = express(); server.use(express.bodyParser()); server.post('/api/v1', function(req, resp) { var body = req.body; //if request header doe ...

Fetching specific information from MySQL using EJS

Check out the Github project here Currently, I am in the process of developing a Quiz creation application using EJS as the templating engine along with jQuery, Bootstrap, and MySql. I have encountered a challenge where I am trying to display the corresp ...

Looking for a Handlebars helper that can determine if a value is greater than 1 or less than 2, and then render specific code based on which condition is satisfied

My login route is saving user data with a permission_id key that needs to be checked to determine whether it is greater than 1 or less than 2. Depending on the value of permission_id, I need to render different HTML content to allow or restrict access to c ...