Vue.js中如何为前缀一致的文件输入框批量执行upload重置操作?
Hey there! The issue here is that the this.$upload.reset() method doesn't support wildcard matching for input names—so those wildcard attempts you tried won't work out of the box. Let's break down two solid approaches to get this done:
1. If Your Inputs Are Dynamically Generated (Recommended)
If you're using v-for to render your file inputs (which is common for array-style inputs), you probably already have a data property tracking how many inputs exist. You can loop through that count to target each input by its exact name:
Example Setup
<template> <div> <!-- Dynamically render file inputs --> <input v-for="(_, index) in totalFileInputs" :key="index" type="file" :name="`file${index}`" /> <button @click="resetAllFileInputs">Reset All</button> </div> </template> <script> export default { data() { return { totalFileInputs: 2 // Adjust this number based on your needs }; }, methods: { resetAllFileInputs() { // Loop through each input name and call reset for (let i = 0; i < this.totalFileInputs; i++) { this.$upload.reset(`file${i}`, { url: 'documentations/upload' }); } } } }; </script>
This approach is clean because it leverages Vue's reactive data instead of touching the DOM directly.
2. If Inputs Are Static or You Prefer DOM-Based Selection
If your inputs are hardcoded or you don't have a reactive count to reference, you can use vanilla JavaScript to select all inputs with a name starting with file, then loop through them to reset each one:
Example Method
resetAllFileInputs() { // Select all file inputs where name starts with "file" const matchingInputs = document.querySelectorAll('input[type="file"][name^="file"]'); // Reset each input individually matchingInputs.forEach(input => { this.$upload.reset(input.name, { url: 'documentations/upload' }); }); }
A quick note: Direct DOM manipulation isn't the most "Vue-like" approach, but it works reliably for static inputs.
Why Wildcards Didn't Work
Most upload libraries (including whatever $upload is in your project) expect an exact input name for the reset() method—they don't include built-in wildcard parsing. That's why your file* and similar attempts didn't trigger any action.
内容的提问来源于stack exchange,提问作者Masterpiece Mas Icang

