在 Vue2 中,可以使用 `el-dialog` 创建弹窗,并在其内部添加按钮和操作逻辑。以下是一个完整的示例,展示如何在 `el-dialog` 弹窗中新增“下载模板”和“上传文件”按钮,并为其绑定相应的操作函数。
### 基本结构
```html
<template>
<div>
<!-- 触发弹窗的按钮 -->
<el-button @click="dialogVisible = true">打开弹窗</el-button>
<!-- 弹窗组件 -->
<el-dialog title="文件操作" :visible.sync="dialogVisible">
<div class="dialog-content">
<!-- 下载模板按钮 -->
<el-button type="primary" @click="downloadTemplate">下载模板</el-button>
<!-- 文件上传区域 -->
<el-upload
action="/api/upload" <!-- 替换为实际的上传接口地址 -->
:on-success="handleUploadSuccess"
:before-upload="beforeUpload"
:limit="1"
:on-exceed="handleExceed"
:file-list="fileList"
>
<el-button type="success">上传文件</el-button>
</el-upload>
</div>
<!-- 底部按钮 -->
<div slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">关 闭</el-button>
</div>
</el-dialog>
</div>
</template>
```
### 脚本部分
```javascript
<script>
export default {
data() {
return {
dialogVisible: false, // 控制弹窗显示状态
fileList: [] // 用于存储已上传的文件列表
};
},
methods: {
// 下载模板方法
downloadTemplate() {
const link = document.createElement('a');
link.href = '/path/to/template.xlsx'; // 替换为实际的模板路径
link.download = '模板.xlsx'; // 指定下载文件名
link.click();
},
// 上传成功回调
handleUploadSuccess(response, file, fileList) {
this.$message.success('文件上传成功');
this.fileList = fileList; // 更新文件列表
},
// 上传前的校验(可选)
beforeUpload(file) {
const isValidType = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
file.type === 'application/vnd.ms-excel';
if (!isValidType) {
this.$message.error('只能上传 Excel 文件');
}
return isValidType;
},
// 超出限制时的处理
handleExceed(files, fileList) {
this.$message.warning('最多只能上传一个文件');
}
}
};
</script>
```
### 样式部分(可选)
```css
<style scoped>
.dialog-content {
margin-bottom: 20px;
}
</style>
```
---
### 说明:
- **`el-dialog`**:控制弹窗的显示与隐藏。
- **`el-button`**:分别用于触发下载模板和上传文件操作。
- **`el-upload`**:Element UI 提供的上传组件,支持多种配置项,如上传限制、文件类型检查等。
- **`downloadTemplate` 方法**:通过创建 `<a>` 标签并设置 `download` 属性实现客户端文件下载。
- **`handleUploadSuccess` 方法**:处理上传成功后的逻辑,例如提示用户或更新文件列表。
- **`beforeUpload` 方法**:对上传文件进行类型校验,防止非法格式文件上传。
- **`handleExceed` 方法**:当用户上传超过限制数量时给出提示。
该代码可在 Vue2 + Element UI 的环境中直接运行[^1]。
---