Vue.js+Axios环境下未选中至少一张图片时阻止表单提交的实现方法
实现方案
核心修改思路
- 新增计算属性判断是否至少有一张图片被选中/上传成功,作为提交按钮的禁用依据
- 给提交按钮绑定
disabled属性,不满足条件时禁止点击 - 给提交表单绑定提交拦截事件,避免用户绕过按钮禁用直接提交
- 优化图片上传逻辑,上传失败时清空对应文件状态,避免校验逻辑误判
完整修改后代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Add Item</title> <script src="https://unpkg.com/vue@next"></script> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <style> /* 可选:禁用按钮样式优化 */ button:disabled { opacity: 0.6; cursor: not-allowed; } </style> </head> <body> <div id="app"> <!-- 绑定提交拦截事件 --> <form name="addItem" method="post" action="/user/addItem" @submit.prevent="handleSubmit"> <label for="name">name</label> <input type="text" id="name" v-model="name"> <!-- 绑定禁用属性 --> <button type="submit" id="submit" :disabled="!canSubmit">Save Item</button> </form> <form @submit.prevent enctype="multipart/form-data"> <input type="file" ref="file1" @change="selectFile1" accept="image/*"> </form> <form @submit.prevent enctype="multipart/form-data"> <input type="file" ref="file2" @change="selectFile2" accept="image/*"> </form> </div> <script> const addProduct = { name: "addProduct", data() { return{ name: '', file1: "", image1:"", file2: "", image2: "", } }, computed: { // 至少有一个文件存在就允许提交,可根据需求调整为判断image1/image2(仅上传成功才允许提交) canSubmit() { return !!(this.file1 || this.file2); // 若要求上传成功才能提交,换成下面这行 // return !!(this.image1 || this.image2); } }, methods:{ async selectFile1(){ this.file1 = this.$refs.file1.files[0]; if (!this.file1) return; const formData = new FormData(); formData.append('file', this.file1); try { const res = await axios.post('/user/uploadImage', formData); // 上传成功后保存后端返回的图片地址 this.image1 = res.data.url; } catch (e) { // 上传失败清空状态 this.file1 = ''; this.image1 = ''; this.$refs.file1.value = ''; alert('图片1上传失败,请重新选择'); } }, async selectFile2(){ this.file2 = this.$refs.file2.files[0]; if (!this.file2) return; const formData = new FormData(); formData.append('file', this.file2); try { const res = await axios.post('/user/uploadImage', formData); this.image2 = res.data.url; } catch (e) { this.file2 = ''; this.image2 = ''; this.$refs.file2.value = ''; alert('图片2上传失败,请重新选择'); } }, handleSubmit() { // 二次校验,避免用户绕过前端禁用规则 if (!this.canSubmit) { alert('请至少选择一张图片后提交'); return; } // 若需要自定义提交逻辑在这里写,不需要的话直接调用表单原生提交 document.forms.addItem.submit(); } } } Vue.createApp(addProduct).mount('#app') </script> </body> </html>
内容的提问来源于stack exchange,提问作者Steve Jobs
相关产品推荐
相关产品推荐

