Rumah > Soal Jawab > teks badan
Saya cuba memuat naik menggunakan api gubahan vue. Walaupun muat naik berfungsi dengan baik, saya ingin menetapkan semula apabila butang tetapan semula diklik, tetapi ia tidak boleh diakses dalam api gubahan $refs.file
或 this.$refs.file
.
<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粉7624473632023-12-27 14:27:58
Apa yang perlu anda lakukan, pada mulanya anda perlu memasukkan komponen getCurrentInstance
,
const instance = getCurrentInstance();
然后您需要执行 instance.refs.file.value = null
Secara ringkasnya, komponen anda sepatutnya kelihatan seperti ini.
<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>