2

i am trying to upload with vue composition api. While the upload is working properly, 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>

3
  • You shouldn't. Don't use $refs with composition api. Commented Nov 23, 2022 at 18:35
  • friend gave the answer below, check it maybe you need it :) Commented Nov 23, 2022 at 18:42
  • This is a hack that is only needed when you deal with legacy code that cannot be adapted to Vue 3 - mixins, etc. Commented Nov 23, 2022 at 18:52

1 Answer 1

5

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

<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>

Sign up to request clarification or add additional context in comments.

1 Comment

Bravo. While this is marked duplicate, this is a clear answer to working with files, which are a bit different than the referenced duplicates.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.