search

Home  >  Q&A  >  body text

How to use 'this.$refs' in Vue 3 composition api?

I'm trying to upload using the vue combo api. While the upload is working fine, I want to reset when the reset button is clicked, but I cannot access $refs.file or this.$refs.file in the composition api.

<template>
  <input type="file" class="absolute w-0 h-0 invisible opacity-0" @change="handleImageSelected" ref="file" accept="image/*">
  <button @click="$refs.file.click()">Upload</button>
  <button @click="resetUploadFile">Reset</button>
</template>

<script setup>
import {ref} from 'vue'

const imageFile = ref()
const imageUrl = ref()

function handleImageSelected(e) {
  if (!e.target.files.length) return;
  imageFile.value = e.target.files[0];
  console.log(e.target.files[0])
  let reader = new FileReader();
  reader.readAsDataURL(imageFile.value);
  reader.onload = e => {
    imageUrl.value = e.target.result;
  };
}

function resetUploadFile() {
  this.$refs.file.target.value = null
  imageFile.value = null
  imageUrl.value = null
}
</script>

P粉420958692P粉420958692372 days ago492

reply all(1)I'll reply

  • P粉762447363

    P粉7624473632023-12-27 14:27:58

    What you have to do, initially you need to include the getCurrentInstance component, const instance = getCurrentInstance();Then you need to do instance.refs.file.value = null In summary, your component should look like this.

    <template>
      <input type="file" class="absolute w-0 h-0 invisible opacity-0" @change="handleImageSelected" ref="file" accept="image/*">
      <button @click="$refs.file.click()">Upload</button>
      <button @click="resetUploadFile">Reset</button>
    </template>
    
    <script setup>
    import {ref, getCurrentInstance} from 'vue'
    
    const instance = getCurrentInstance()
    const imageFile = ref()
    const imageUrl = ref()
    
    function handleImageSelected(e) {
      if (!e.target.files.length) return;
      imageFile.value = e.target.files[0];
      console.log(e.target.files[0])
      let reader = new FileReader();
      reader.readAsDataURL(imageFile.value);
      reader.onload = e => {
        imageUrl.value = e.target.result;
      };
    }
    
    function resetUploadFile() {
      instance.refs.file.value = null
      imageFile.value = null
      imageUrl.value = null
    }
    </script>

    reply
    0
  • Cancelreply