Vue2多图上传如何点击叉号仅删除单张选中的已上传预览图片
问题根因
- 原代码删除按钮写在了图片
v-for循环外,所有图片仅对应一个公共删除按钮 removeImage方法直接将images整体设为null,没有按索引删除单张资源- 原生
FileList是只读类数组对象,无法直接删除元素,需要转成普通数组存储 - 存在方法名拼写不一致问题:模板中调用
submitFiles,实际定义的方法名为submitFile
修复后代码
JavaScript部分
Vue.config.productionTip = false; new Vue({ el: '#app', data() { return { // 改为普通数组存储文件,支持删除操作 files: [], images: [], } }, computed: { filesNames() { return this.files.map(file => file.name) } }, methods: { handleFileUploads(event) { // 将只读的FileList转成普通数组存储 this.files = Array.from(event.target.files); this.images = this.files.map(URL.createObjectURL); }, // 接收索引参数,删除对应位置的图片和文件记录 removeImage: function (index) { this.images.splice(index, 1) this.files.splice(index, 1) }, // 修正方法名和模板调用保持一致 submitFiles() { let formData = new FormData(); for (var i = 0; i < this.files.length; i++) { let file = this.files[i]; formData.append('files[' + i + ']', file); } axios.post('/multiple-files', formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(function() { console.log('SUCCESS!!'); }) .catch(function() { console.log('FAILURE!!'); }); } } })
HTML部分
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <div id="app"> <h2>多文件上传</h2> <hr/> <label> <span>选择文件</span> <input type="file" multiple @change="handleFileUploads($event)" /> <ul v-if="files.length"> <li v-for="(name, i) in filesNames" :key="i">{{ name }}</li> </ul> </label> <div style="display: flex; gap: 10px; margin-top: 10px;"> <!-- 把图片和删除按钮放到同一循环块,每个图片对应独立删除按钮 --> <div v-for="(image, index) in images" :key="index" style="position: relative;"> <img :src="image" style="width: 100px; height: 100px; object-fit: cover;" /> <!-- 传递当前索引到删除方法,内置样式实现右上角叉号效果 --> <button @click="removeImage(index)" type="button" style="position: absolute; top: -5px; right: -5px; width: 20px; height: 20px; border-radius: 50%; background: #fff; border: 1px solid #ccc; cursor: pointer; padding: 0;"> × </button> </div> </div> <br /> <button @click="submitFiles">提交</button> </div>
代码中内置了简易布局样式实现右上角叉号效果,不需要可自行移除。
内容的提问来源于stack exchange,提问作者Inayat Kazi
相关产品推荐
相关产品推荐

