前提
Vue 3.0 + Element Plus
使用手动上传,写了两个按钮,分别是“上传文件”和“进入分析”
预想
点击“上传文件”会弹出文件选择器进行文件选择
点击“进入分析”会调用函数将文件传送到后端
问题
点击“进入分析”后也会弹出文件选择器
原因分析
两个按钮共用一个input,会触发两次input的click事件
参考 https://www.cnblogs.com/naxwnm/p/14277822.html
原代码
HTML
<el-upload ref="upload" v-model:file-list="fileList" class="upload-file" :limit="3" multiple action="/upload"
:on-exceed="handleExceed" :before-upload="fileFilter" :on-success="fileUploaded" :auto-upload="false"
:data="uploadParam">
<el-button type="primary" slot="trigger">点击上传</el-button>
<el-button style="margin-left: 2em;" type="success" @click="submitUpload">进入分析</el-button>
<template #tip>
<div class="el-upload__tip">
仅支持json文件
</div>
</template>
</el-upload>
JavaScript
export default {
methods: {
submitUpload() {
this.$refs.upload.submit();
},
}
}
修改后
仅修改HTML代码,加一层template
<el-upload ref="upload" v-model:file-list="fileList" class="upload-file" :limit="3" multiple action="/upload"
:on-exceed="handleExceed" :before-upload="fileFilter" :on-success="fileUploaded" :auto-upload="false"
:data="uploadParam">
<template #trigger>
<el-button type="primary">点击上传</el-button>
</template>
<el-button style="margin-left: 2em;" type="success" @click="submitUpload">进入分析</el-button>
<template #tip>
<div class="el-upload__tip">
仅支持json文件
</div>
</template>
</el-upload>
补充
在评论区中用户Moirrra提出了一种更简单的解决方法,就是把”进入分析“那个button的@click改为@click.stop即可,修改后如下
<el-upload ref="upload" v-model:file-list="fileList" class="upload-file" :limit="3" multiple action="/upload"
:on-exceed="handleExceed" :before-upload="fileFilter" :on-success="fileUploaded" :auto-upload="false"
:data="uploadParam">
<el-button type="primary" slot="trigger">点击上传</el-button>
<el-button style="margin-left: 2em;" type="success" @click.stop="submitUpload">进入分析</el-button>
<template #tip>
<div class="el-upload__tip">
仅支持json文件
</div>
</template>
</el-upload>