Reputation: 11
I've been trying to create a simple drag and drop component but I'm having problem selecting the div using getElementById
. what am I doing wrong here? the error says: Uncaught TypeError: Cannot read property 'addEventListener' of null
.
also the console log gives null
instead of the 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>
Upvotes: 1
Views: 830
Reputation: 3830
In Vuejs you need to put your function inside the method
object of your component.
And you also need to put the logic that needs to be run when the component is mounted inside the mounted
object.
https://v2.vuejs.org/v2/guide/
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() {
// Put logic that needs to be 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);
},
};
Also it is better to use ref
if you want to access the dom.
See Here
You can read the vuejs doc to better understand how Vuejs works. https://vuejs.org/
Upvotes: 2