[Vuejs]-How to make clickable images that acts like input file

1👍

Try to bind ref (:ref):

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const fileInputRefs = ref([])
    const handleImageClick = (index) => {
      fileInputRefs.value[index].click()
    }
    const handleFileUpload = (event, id) => {
      const fileList = event.target.files
      const reader = new FileReader()
      reader.readAsDataURL(fileList[0])
      reader.onload = () => {
        if (id === 'image1') {
          fileInputRefs.value = {
            file: fileList[0],
            dataUrl: reader.result
          }
        } else if (id === 'image2') {
          fileInputRefs.value[1] = {
            file: fileList[0],
            dataUrl: reader.result
          }
        }
      }
    }
    return {
      handleImageClick, handleFileUpload, fileInputRefs
    };
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <input class="form-control" type="file" @change="handleFileUpload($event, 'image1')" 
     :ref="el => { fileInputRefs[0] = el }" style="display: none;">
  <img src="front.png" class="images" @click="handleImageClick(0)">

  <input class="form-control" type="file" @change="handleFileUpload($event, 'image2')" 
    :ref="el => { fileInputRefs[1] = el }" style="display: none;">
  <img src="back.png" class="images" @click="handleImageClick(1)">
</div>

Leave a comment