How to use 'this.$refs' in Vue 3 composition api?
P粉420958692
P粉420958692 2023-12-26 16:42:38
0
1
472

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粉420958692
P粉420958692

reply all(1)
P粉762447363

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template