I am faced with the challenge of creating a clickable image that simulates an input file and captures the file name using Vue 3. However, I continuously encounter the error
Uncaught TypeError: Cannot read properties of null (reading 'click')
when attempting to click on the image.
Below is my code snippet:
<template>
<input class="form-control" type="file" @change="handleFileUpload($event, 'image1')"ref="fileInputRefs[0]" style="display: none;">
<img src="front.png" class="images" @click="handleImageClick(0)">
<input class="form-control" type="file" @change="handleFileUpload($event, 'image1')"ref="fileInputRefs[1]" style="display: none;">
<img src="back.png" class="images" @click="handleImageClick(1)">
<script setup>
const fileInputRefs = [
ref(null),
ref(null)
]
const handleImageClick = (index) => {
fileInputRefs[index].value.click()
}
const handleFileUpload = (event, id) => {
const fileList = event.target.files
const reader = new FileReader()
reader.readAsDataURL(fileList[0])
reader.onload = () => {
if (id === 'image1') {
file1.value = {
file: fileList[0],
dataUrl: reader.result
}
} else if (id === 'image2') {
file2.value = {
file: fileList[0],
dataUrl: reader.result
}
}
}
}
</script>