el-upload实现文件上传(包括预览,下载)建议直接看第二种方法

一、以卡片形式上传、预览、下载文件(下载预览功能没写好)

(1)父组件


<template>
	<el-container class="h100">
		<el-aside class="h100" width="41rem">
			<div class="leftbk">
				<div class="tableTitle mt0">
					待提交(<span class="tableTitleFont wait">{{ staticNum.ready }}</span
					>)审批中(<span class="tableTitleFont wait">{{ staticNum.appealing }}</span
					>)
				</div>
				<el-form :model="leftForm" ref="leftForm" class="leftForm">
					<el-col :span="18">
						<el-form-item label="提交时间:" prop="appealDate" label-width="100px">
							<el-date-picker
								v-model="leftForm.appealDate"
								type="daterange"
								align="right"
								unlink-panels
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								:picker-options="pickerOptions"
								value-format="yyyy-MM-dd"
							>
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="rightButton">
							<el-button type="primary" @click="searchLeftForm">查询</el-button>
							<el-button plain @click="resetLeftForm">重置</el-button>
						</el-form-item>
					</el-col>
				</el-form>
				<el-table :data="tableDataReady" highlight-current-row border height="calc((100% - 12rem)/2)" @row-click="rowClick" ref="readyTable" :cell-class-name="appealStatusClass">
					<el-table-column type="index" width="55" label="序号" align="center"> </el-table-column>
					<el-table-column property="appealDescribe" label="申请描述" align="center" min-width="75" show-overflow-tooltip></el-table-column>
					<el-table-column prop="appealFlag" label="状态" align="center" min-width="80" filter-placement="bottom-end" :formatter="seasonAppealFlagFormat"> </el-table-column>
					<el-table-column property="appealCompany" label="申请航司" align="center" min-width="80" show-overflow-tooltip></el-table-column>
					<el-table-column property="appealTime" label="提交时间" align="center" min-width="120" :formatter="timeFormat"></el-table-column>
					<el-table-column fixed="right" label="操作" width="100" align="center">
						<template slot-scope="scope">
							<el-link type="primary" @click.stop="removeAction(scope.row)" v-if="scope.row.appealFlag == '0'">删除</el-link>
						</template>
					</el-table-column>
				</el-table>

				<div class="tableTitle">
					已审批( <span class="tableTitleFont ok">已批复:{{ staticNum.ok }}</span
					>&nbsp;&nbsp;&nbsp;<span class="tableTitleFont error">被退回:{{ staticNum.error }}</span> )
				</div>
				<el-form :model="leftBottomForm" ref="leftBottomForm" class="leftForm">
					<el-col :span="18">
						<el-form-item label="提交时间:" prop="approvalDate" label-width="100px">
							<el-date-picker
								v-model="leftBottomForm.approvalDate"
								type="daterange"
								align="right"
								unlink-panels
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								:picker-options="pickerOptions"
								value-format="yyyy-MM-dd"
							>
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="rightButton">
							<el-button type="primary" @click="searchLeftBottomForm">查询</el-button>
							<el-button plain @click="resetLeftBottomForm">重置</el-button>
						</el-form-item>
					</el-col>
				</el-form>
				<el-table :data="tableDataResult" highlight-current-row border height="calc((100% - 12rem)/2)" @row-click="rowClick" :cell-class-name="appealStatusClass">
					<el-table-column type="index" width="55" label="序号" align="center"> </el-table-column>
					<el-table-column property="appealDescribe" label="申请描述" align="center" min-width="75" show-overflow-tooltip></el-table-column>
					<el-table-column prop="appealFlag" label="状态" align="center" min-width="80" filter-placement="bottom-end" :formatter="seasonAppealFlagFormat"> </el-table-column>
					<el-table-column property="appealCompany" label="申请航司" align="center" min-width="80" show-overflow-tooltip></el-table-column>
					<el-table-column property="appealTime" label="提交时间" align="center" min-width="120" :formatter="timeFormat"></el-table-column>

					<!-- <el-table-column fixed="right" label="操作" width="100" align="center">
						<template slot-scope="scope">
							<el-link type="primary" @click.stop="removeAction(scope.row)" v-if="scope.row.appealFlag == '0'">删除</el-link>
						</template>
					</el-table-column> -->
				</el-table>
			</div>
		</el-aside>
		<el-main>
			<div class="waitCommit">
				<div class="tableTitle">时刻详情</div>
				<div class="reAppeal"><el-button type="primary" v-show="selectAppealFlag == '2'" @click="reAppeal()">重新申请</el-button></div>
				<el-button type="primary" v-show="couldReceive" class="receiveBtn" @click="receive">取回</el-button>
				<div :class="{ approveBg: isAgree, rejectBg: !isAgree }" v-show="approveShow"></div>
			</div>
			<el-form :model="ruleForm" ref="ruleForm" class="demo-ruleForm">
				<el-form-item label="描述信息" prop="appealDescribe" label-width="100px">
					<el-input v-model="ruleForm.appealDescribe" maxlength="20"></el-input>
				</el-form-item>
				<el-form-item class="mainForm">
					<el-col :span="7">
						<el-form-item label="申请航司" prop="icao" label-width="100px">
							<el-input v-model="ruleForm.icao" readonly></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="7">
						<el-form-item label="申请时间" prop="appealTime" label-width="100px">
							<el-input v-model="ruleForm.appealTime" readonly></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="7">
						<el-form-item label="申请人" prop="appealBy" label-width="100px">
							<el-input v-model="ruleForm.appealBy" readonly></el-input>
						</el-form-item>
					</el-col>
					<!-- <el-col :span="3" class="addDiv">
						<el-button type="primary" @click="addTime">添加</el-button>
					</el-col> -->
				</el-form-item>
				<!-- <el-form-item class="mainForm">
					<el-col :span="14">
						<el-form-item label="班期" prop="weekly" label-width="100px">
							<el-checkbox-group v-model="ruleForm.weekly">
								<el-checkbox :label="item.id" v-for="item in weekList" :key="item.id">{{ item.text }}</el-checkbox>
							</el-checkbox-group>
						</el-form-item>
					</el-col>

					<el-col :span="10">
						<el-form-item label="日期范围" prop="timeRange" label-width="100px">
							<el-date-picker v-model="ruleForm.timeRange" type="daterange" align="right" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" :picker-options="pickerOptions" style="width: 100%"> </el-date-picker>
						</el-form-item>
					</el-col>
				</el-form-item> -->
				<!-- <el-form-item label="选择交换航司" prop="nextCompany" label-width="140px">
					<el-select v-model="ruleForm.nextCompany" filterable placeholder="请选择" style="width: 100%" clearable>
						<el-option v-for="item in companyList" :key="item.icao" :label="item.icao + '/' + item.nameCn" :value="item.icao"> </el-option>
					</el-select>
				</el-form-item> -->
			</el-form>
			<div>时刻信息</div>
			<el-table :data="tableData" border style="width: 100%">
				<el-table-column prop="momentTime" label="时刻" width="180" align="center"> </el-table-column>
				<el-table-column prop="airport" label="机场" align="center" min-width="100"> </el-table-column>
				<el-table-column prop="weeklyArrangement" label="班期" min-width="180" align="center"> </el-table-column>
				<el-table-column prop="startDate" label="开始日期" width="180" align="center" :formatter="dateFormat"> </el-table-column>
				<el-table-column prop="endDate" label="结束日期" width="180" align="center" :formatter="dateFormat"> </el-table-column>
				<!-- <el-table-column label="操作" align="center">
					<template slot-scope="scope">
						<el-link type="primary" @click="deleteRow(scope.$index, tableData)">删除</el-link>
					</template>
				</el-table-column> -->
			</el-table>
			<div>说明信息</div>
			<el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="ruleForm.appealExplain" resize="none"> </el-input>
			<div>文件信息</div>
			<!-- 文件上传 -->
			<LesUpload @onSuccess="fileUploadSuccess" @onRemoveFile="handleRemove" :fileList="appealFileList"></LesUpload>

			<div class="footerDiv" v-show="!haveResult && !couldReceive">
				<el-button type="primary" @click="submit">提交</el-button>
				<el-button plain @click="reset">重置</el-button>
			</div>
		</el-main>

		<!-- 重新申请,新增 -->
		<SeasonTimeAdd
			:seasonTimeAddData.sync="seasonTimeAddData"
			:fileList="appealFileList"
			:seasonTimeAddTableData="tableData"
			:dialogFormVisible.sync="dialogFormVisible"
			@handelFormVisible="setFormVisible"
		></SeasonTimeAdd>
		<!-- 重新申请,归还 -->
		<SeasonTimeReturn
			:seasonTimeReturnInputData="seasonTimeReturnInputData"
			:seasonTimeReturnData.sync="tableData"
			:fileList="appealFileList"
			:dialogFormReturnVisible.sync="dialogFormReturnVisible"
			@handelFormVisible="setFormReturnVisible"
		></SeasonTimeReturn>
	</el-container>
</template>

<script>
import {
	queryAppeal,
	pagePubAppeal,
	queryAppealFileByAppealUuid,
	queryApproveByAppealUuid,
	queryImitateByAppealUuid,
	updateAppeal,
	submitAppeal,
	callBackAppeal,
	removeAppeal,
} from '@/api/interface/time-manage/season-time-company-appeal.js';
import LesUpload from '@/components/LesUpload/index.vue';
import SeasonTimeAdd from '@/views/time-manage/season-time-add/season-time-add.vue';
import SeasonTimeReturn from '@/views/time-manage/season-time-return/season-time-return.vue';

export default {
	name: 'SeasonTimeAddAppeal',
	components: {
		LesUpload,
		SeasonTimeAdd,
		SeasonTimeReturn,
	},

	props: {
		// 是新增还是归还
		appealType: {
			type: String,
			default: '',
		},
	},

	data() {
		return {
			id: '',
			selectTaskId: '',
			// 是否有审批结果的显隐
			haveResult: true,

			//是否可以回收
			couldReceive: false,
			isDisable: {
				form: true,
			},

			// // 组件选值列表
			// list: {
			// 	season: [],
			// 	company: [],
			// },

			//左侧申请表单统计数据
			staticNum: {
				ready: 0,
				appealing: 0,
				ok: 0,
				error: 0,
			},

			// 表单参数
			leftForm: {
				appealDate: [],
				startDate: '',
				stopDate: '',
			},
			leftBottomForm: {
				apppovalDate: [],
				startDate: '',
				stopDate: '',
			},

			// 表单参数
			form: {
				appealCompany: '',
				appealCompanyName: '',
				appealDescribe: '',
				appealTime: '',
				appealExplain: '',
				appealBy: '',
			},
			// 待提交
			tableDataReady: [],
			// 审批中
			tableDataWaiting: [],
			// 已审批
			tableDataResult: [],

			pickerOptions: {
				shortcuts: [
					{
						text: '最近一周',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
							picker.$emit('pick', [start, end]);
						},
					},
					{
						text: '最近一个月',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
							picker.$emit('pick', [start, end]);
						},
					},
					{
						text: '最近三个月',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
							picker.$emit('pick', [start, end]);
						},
					},
				],
			},

			// 右侧表单表格数据
			ruleForm: {
				appealDescribe: '',
				icao: this.$UserInfoUtil.getIcao(),
				// airport: '',
				// weekly: [],
				// weeklyArrangement: '',
				// timeRange: [],
				startDate: '',
				endDate: '',
				appealExplain: '',
				appealBy: '',
				appealTime: '',
			},
			// 周期
			weekList: [
				{ id: '1', text: '周一' },
				{ id: '2', text: '周二' },
				{ id: '3', text: '周三' },
				{ id: '4', text: '周四' },
				{ id: '5', text: '周五' },
				{ id: '6', text: '周六' },
				{ id: '7', text: '周日' },
			],
			tableData: [],
			appealFileList: [], //文件信息
			companyList: [],

			approveShow: false, //是否显示审批背景图
			isAgree: false, //审批背景图样式

			// 选中的行数据状态
			selectAppealFlag: '',
			seasonTimeAddData: {}, //重新申请传参
			dialogFormVisible: false,
			bizType: 'MOMENT_ADD',
			dialogFormReturnVisible: false, //时刻归还显隐
			seasonTimeReturnInputData: {}, // 归还表单数据
		};
	},
	methods: {
		// 查询表格
		search() {
			// 清空右侧所有数据
			// 申请时刻信息列表
			this.tableData = [];
			// 审批结果表
			this.approvalTable = [];
			// 选中的行数据状态
			this.selectAppealFlag = '';
			// 控制显隐
			this.dialogFormVisible = false;
			// 选中的行数据
			this.selectData = [];
			// 选中的数据,描述和说明
			this.inputData = {};
			this.appealFileList = []; //文件信息
			// 是否有审批结果的显隐
			this.haveResult = true;
			//是否可以回收
			this.couldReceive = false;
			this.isDisable = {
				form: true,
			};

			this.getQueryAppeal();
			this.getPagePubAppeal();

			// // 获取待提交和审批中
			// queryAppeal({ seasonOrDaily: '1', bizType: this.bizType, preTask: '-1' }).then((res) => {
			// 	if (res.data.code == '1') {
			// 		let appealList = res.data.data;
			// 		this.tableDataReady = res.data.data == null ? [] : res.data.data;
			// 		let readyList = appealList.filter((item) => {
			// 			return item.appealFlag == '0';
			// 		});
			// 		this.$set(this.staticNum, 'ready', readyList.length);
			// 		let waitList = appealList.filter((item) => {
			// 			return item.appealFlag == '1';
			// 		});
			// 		this.$set(this.staticNum, 'appealing', waitList.length);
			// 	} else {
			// 		this.tableDataReady = [];
			// 		this.staticNum = {
			// 			ready: 0,
			// 			appealing: 0,
			// 		};
			// 		this.couldReceive = false;
			// 		this.haveResult = true;
			// 		this.id = '';
			// 	}
			// });

			// // 获取已审批记录
			// pagePubAppeal({ appealCompany: this.$UserInfoUtil.getIcao(), seasonUuid: this.leftForm.season, seasonOrDaily: '1', bizType: this.bizType, preTask: '-1' }).then((res) => {
			// 	if (res.data.code == '1') {
			// 		let approvalReasult = res.data.data;
			// 		this.tableDataResult = res.data.data == null ? [] : res.data.data;
			// 		let approvalList = approvalReasult.filter((item) => {
			// 			return item.appealFlag != '1' && item.appealFlag != '0';
			// 		});
			// 		let tempOk = approvalList.filter((item) => {
			// 			return item.appealFlag == '3';
			// 		});
			// 		this.$set(this.staticNum, 'ok', tempOk.length);
			// 		let tempError = approvalList.filter((item) => {
			// 			return item.appealFlag == '2';
			// 		});
			// 		this.$set(this.staticNum, 'error', tempError.length);
			// 	} else {
			// 		this.tableDataResult = [];
			// 		this.staticNum.ok = 0;
			// 		this.staticNum.error = 0;
			// 	}
			// });
		},

		getQueryAppeal() {
			// 获取待提交和审批中
			queryAppeal({ seasonOrDaily: '1', bizType: this.bizType, preTask: '-1', ...this.leftForm }).then((res) => {
				if (res.data.code == '1') {
					let appealList = res.data.data;
					this.tableDataReady = res.data.data == null ? [] : res.data.data;
					let readyList = appealList.filter((item) => {
						return item.appealFlag == '0';
					});
					this.$set(this.staticNum, 'ready', readyList.length);
					let waitList = appealList.filter((item) => {
						return item.appealFlag == '1';
					});
					this.$set(this.staticNum, 'appealing', waitList.length);
				} else {
					this.tableDataReady = [];
					this.staticNum = {
						ready: 0,
						appealing: 0,
					};
					this.couldReceive = false;
					this.haveResult = true;
					this.id = '';
				}
			});
		},

		getPagePubAppeal() {
			// 获取已审批记录
			pagePubAppeal({ appealCompany: this.$UserInfoUtil.getIcao(), seasonOrDaily: '1', bizType: this.bizType, preTask: '-1', ...this.leftBottomForm }).then((res) => {
				if (res.data.code == '1') {
					let approvalReasult = res.data.data;
					this.tableDataResult = res.data.data == null ? [] : res.data.data;
					let approvalList = approvalReasult.filter((item) => {
						return item.appealFlag != '1' && item.appealFlag != '0';
					});
					let tempOk = approvalList.filter((item) => {
						return item.appealFlag == '3';
					});
					this.$set(this.staticNum, 'ok', tempOk.length);
					let tempError = approvalList.filter((item) => {
						return item.appealFlag == '2';
					});
					this.$set(this.staticNum, 'error', tempError.length);
				} else {
					this.tableDataResult = [];
					this.staticNum.ok = 0;
					this.staticNum.error = 0;
				}
			});
		},

		// 时间渲染
		timeFormat(row, column, cellValue, index) {
			if (cellValue != null && cellValue != '') {
				return this.moment(cellValue).format('YYYY-MM-DD HH:mm');
			}
		},
		rowClick(row, column, cell, event) {
			this.id = row.id;
			this.selectTaskId = row.taskId;
			this.selectAppealFlag = row.appealFlag;
			this.ruleForm.appealCompany = row.appealCompany;
			this.ruleForm.appealDescribe = row.appealDescribe;
			this.ruleForm.appealTime = row.appealTime;
			// this.ruleForm.airport = row.airport;
			this.ruleForm.appealExplain = row.appealExplain;
			this.ruleForm.appealBy = row.appealBy;

			// 是新增还是归还
			if (this.bizType == 'MOMENT_ADD') {
				this.seasonTimeAddData = row;
			} else {
				this.seasonTimeReturnInputData = row;
			}

			// 显示右侧的同意和驳回背景图
			if (row.appealFlag == '2' || row.appealFlag == '3') {
				this.approveShow = true;
				if (row.appealFlag == '2') {
					this.isAgree = false;
				} else {
					this.isAgree = true;
				}
			} else {
				this.approveShow = false;
			}

			this.inputData = {
				appealDescribe: row.appealDescribe,
				appealExplain: row.appealExplain,
				id: row.id,
				// planId: row.bizId,
			};
			this.appealFileList = [];
			// 查询右侧顶部信息
			queryApproveByAppealUuid({ appealUuid: row.id, seasonOrDaily: '1' }).then((res) => {
				// // 如果是待审批
				if (row.appealFlag == '1' && res.data.data && res.data.data.length == 0) {
					this.couldReceive = true;
					this.haveResult = false;
					this.isDisable.form = true;
				} else {
					if (row.appealFlag == '0') {
						this.couldReceive = false;
						this.haveResult = false;
						this.isDisable.form = false;
					} else {
						this.couldReceive = false;
						this.haveResult = true;
						this.isDisable.form = true;
					}
				}
				this.approvalTable = res.data.data;
			});
			// 查询右侧文件信息
			queryAppealFileByAppealUuid({ appealUuid: row.id, seasonOrDaily: '1' }).then((res) => {
				this.appealFileList = res.data.data == null ? [] : res.data.data;
				this.appealFileList.forEach((element, index) => {
					this.$set(this.appealFileList[index], 'name', element.fileName);
				});
			});

			// 查询右侧表格数据
			queryImitateByAppealUuid({ appealUuid: row.id, seasonOrDaily: '1' }).then((res) => {
				this.tableData = res.data.data;
				// 选中的数据
				this.selectData = res.data.data;
			});
		},
		// 日期渲染
		dateFormat(row, column, cellValue, index) {
			if (cellValue != null && cellValue != '') {
				return this.moment(cellValue).format('YYYY-MM-DD');
			}
		},
		// 重新申请
		reAppeal() {
			if (this.bizType == 'MOMENT_ADD') {
				this.dialogFormVisible = true;
			} else {
				this.dialogFormReturnVisible = true;
			}
		},
		setDialogVisible(val) {
			this.dialogFormVisible = val.dialogFormVisible;
			this.search();
		},

		// 取回
		receive() {
			this.$secondConfirm('确定取回吗?').then((res) => {
				if (res) {
					callBackAppeal({ id: this.id, taskId: this.selectTaskId, bizType: this.bizType, seasonOrDaily: '1' }).then((res) => {
						if (res.data.code == 1) {
							this.$message({
								message: '取回成功!',
								type: 'success',
								showClose: true,
							});
							this.search();
						}
					});
				} else {
					this.$message({
						message: '已取消取回!',
						type: 'info',
						showClose: true,
					});
				}
			});
		},
		// // 根据
		// queryBySeason() {
		// 	this.search();
		// },
		submit() {
			let obj = {};
			obj.id = this.id;
			// obj.appealBy = this.$UserInfoUtil.getCurrentUserId();
			// obj.appealCompany = this.$UserInfoUtil.getIcao();
			this.appealFileList.forEach((element, index) => {
				this.$set(this.appealFileList[index], 'fileName', element.name);
			});
			obj.appealFileList = this.appealFileList.length == 0 ? [] : this.appealFileList;
			obj.appealDescribe = this.ruleForm.appealDescribe;
			obj.appealExplain = this.ruleForm.appealExplain;
			obj.bizType = this.bizType;
			obj.seasonOrDaily = '1';
			obj.appealMomentList = this.tableData;
			this.$secondConfirm('确认提交吗?').then((res) => {
				if (res) {
					updateAppeal(obj).then((res) => {
						if (res.data.code == 1) {
							// this.search();
						} else {
							this.$message({
								message: res.data.msg,
								type: 'warning',
							});
						}
					});
					let tempObj = {};
					tempObj.bizType = this.bizType;
					tempObj.seasonOrDaily = '1';
					tempObj.id = this.id;
					tempObj.taskId = this.selectTaskId;
					submitAppeal(tempObj).then((res) => {
						if (res.data.code == '1') {
							this.$message({
								message: '提交成功!',
								type: 'success',
								showClose: true,
							});
							this.search();
						} else {
							this.$message({
								message: res.data.msg,
								type: 'warning',
								showClose: true,
							});
						}
					});
				} else {
					this.$message({
						message: '已取消',
						type: 'info',
						showClose: true,
					});
				}
			});
		},
		reset() {
			this.ruleForm.appealDescribe = '';
			this.ruleForm.appealExplain = '';
		},

		// 文件删除
		handleRemove(file, fileList) {
			this.appealFileList = fileList;
		},

		// 文件上传成功
		fileUploadSuccess(response, file, fileList) {
			if (response.code == '1') {
				this.appealFileList.push(response.data[0]);
			} else {
				this.$message({
					showClose: true,
					message: '上传失败',
					type: 'error',
				});
			}
		},
		// 查询,重置
		searchLeftForm() {
			if (this.leftForm.appealDate.length == 0) {
				this.leftForm.startDate = '';
				this.leftForm.stopDate = '';
			} else {
				this.leftForm.startDate = this.leftForm.appealDate[0] + ' 00:00:00';
				this.leftForm.stopDate = this.leftForm.appealDate[1] + ' 23:59:59';
			}
			this.getQueryAppeal();
		},
		// 重置
		resetLeftForm() {
			this.$refs.leftForm.resetFields();
			this.searchLeftForm();
		},
		searchLeftBottomForm() {
			if (this.leftBottomForm.apppovalDate.length == 0) {
				this.leftBottomForm.startDate = '';
				this.leftBottomForm.stopDate = '';
			} else {
				this.leftBottomForm.startDate = this.leftBottomForm.apppovalDate[0] + ' 00:00:00';
				this.leftBottomForm.stopDate = this.leftBottomForm.apppovalDate[1] + ' 23:59:59';
			}
			this.getPagePubAppeal();
		},
		resetLeftBottomForm() {
			this.$refs.leftBottomForm.resetFields();
			this.getPagePubAppeal();
		},

		approveFlagFormat(row, column, cellValue, index) {
			if (cellValue != null && cellValue != '') {
				return this.$common.renderCode(cellValue, this.approveFlagList);
			} else {
				return '';
			}
		},

		seasonAppealFlagFormat(row, column, cellValue, index) {
			if (cellValue) {
				return this.$common.renderCode(cellValue, this.appealFlagList);
			} else {
				return '';
			}
		},

		// 审批结果列颜色渲染
		approveFlagClass({ row, column, rowIndex, columnIndex }) {
			if (column.property == 'approveFlag') {
				if (row.approveFlag == '0') {
					return 'approvalError';
				} else {
					return 'approvalOk';
				}
			}
		},

		// 申诉情况列颜色渲染
		appealStatusClass({ row, column, rowIndex, columnIndex }) {
			if (column.property == 'appealFlag') {
				switch (row.appealFlag) {
					case '0':
					case '1':
						return 'appealWait';
						break;
					case '2':
						return 'appealError';
						break;
					case '3':
						return 'appealOk';
						break;
				}
			}
		},

		//将时间转为标准yyyy-MM-dd类型
		formatterDate(stringDate) {
			let formatDate = '';
			if (stringDate) {
				formatDate = this.moment(stringDate).format('YYYY-MM-DD');
				//formatDate = stringDate.substr(0, 4) + '-' + stringDate.substr(4, 2) + '-' + stringDate.substr(6, 2);
			}
			return formatDate;
		},

		// 删除
		removeAction(row) {
			this.$secondConfirm('确认删除吗?').then((res) => {
				if (res) {
					removeAppeal({ appealUuid: row.id, seasonOrDaily: '1', bizType: this.bizType }).then((res) => {
						if (res.data.code == '1') {
							this.$message({
								message: '删除成功!',
								type: 'success',
								showClose: true,
							});
							this.search();
						}
					});
				} else {
					this.$message({
						message: '已取消!',
						type: 'info',
						showClose: true,
					});
				}
			});
		},

		// 新增回调
		setFormVisible(val) {
			this.dialogFormVisible = val.dialogFormVisible;
		},

		// 时刻归还回调
		setFormReturnVisible(val) {
			this.dialogFormReturnVisible = val.dialogFormReturnVisible;
		},
	},

	async mounted() {
		await this.$common.getBizDataByType({ type: 'seasonAppealFlag' }).then((res) => {
			this.appealFlagList = res;
		});
		await this.$common.getBizDataByType({ type: 'approveFlag' }).then((res) => {
			this.approveFlagList = res;
		});
		this.$common.getSelectCompanyData().then((res) => {
			this.companyList = res;
		});

		if (this.appealType == 'timeReturn') {
			this.bizType = 'MOMENT_RETURN';
		} else {
			this.bizType = 'MOMENT_ADD';
		}

		this.search();
		// 收审批消息刷页面
		let that = this;
		window.addEventListener('message', function (ev) {
			let topic = ev.data.topic;
			if ((this.bizType = 'MOMENT_RETURN')) {
				if (topic == 'MOMENT_RETURN_SAVE' || topic == 'MOMENT_RETURN_PUB' || topic == 'MOMENT_RETURN_CALLBACK' || topic == 'MOMENT_RETURN_APPROVE') {
					that.search();
				}
			} else {
				if (topic == 'MOMENT_ADD_SAVE' || topic == 'MOMENT_ADD_PUB' || topic == 'MOMENT_ADD_CALLBACK' || topic == 'MOMENT_ADD_APPROVE') {
					that.search();
				}
			}
		});
	},
};
</script>

<style scoped>
.bk {
	background-color: #ffffff;
	width: 100%;
	min-height: 100%;
	padding: 15px;
}
.leftbk {
	background-color: #ffffff;
	width: 100%;
	height: 100%;
	padding: 0px 15px 0px 0px;
}
.el-card__body,
.el-main {
	padding: 0px;
	padding-left: 20px;
}
.h1090 {
	height: 1090px;
}
.titleTip {
	font-size: 18px;
	font-family: Microsoft YaHei, Microsoft YaHei-Bold;
	font-weight: 700;
	text-align: left;
	color: #546a79;
	line-height: 31px;
	letter-spacing: 0.45px;
	/* margin-top: 16px; */
	margin-bottom: 8px;
}
.m0 {
	margin-top: 0;
}
.el-input--medium {
	font-size: 16px;
}
.el-textarea__inner {
	line-height: 2;
	font-family: Microsoft YaHei, Microsoft YaHei-Regular;
	font-weight: 400;
	text-align: left;
	color: #546a79;
	line-height: 31px;
	letter-spacing: 0.4px;
}

.el-table >>> .appealOk .cell {
	color: #89b336;
}
.el-table >>> .appealWait .cell {
	color: #b38e36;
}
.el-table >>> .appealError .cell {
	color: #cc2c00;
}

.el-table >>> .approvalOk .cell {
	color: #00cd22;
}

.el-table >>> .approvalError .cell {
	color: #cd3f00;
}

.tableTitle {
	/* margin-top: 24px;
	margin-bottom: 16px; */
	line-height: 40px;
	font-size: 24px;
	font-family: Microsoft YaHei, Microsoft YaHei-Bold;
	font-weight: 700;
	color: #0074cd;
	line-height: 32px;
	letter-spacing: 0.6px;
}

.tableTitleFont {
	font-size: 24px;
	font-family: Microsoft YaHei, Microsoft YaHei-Bold;
	font-weight: 700;
	line-height: 31px;
	letter-spacing: 0.6px;
}
.wait {
	color: #e5a117;
}
.ok {
	color: #00cd22;
}
.error {
	color: #cd3f00;
}
.waitCommit {
	position: relative;
	margin-top: 0px;
	display: flex;
	height: 40px;
	justify-content: space-between;
}

/* .el-col >>> .el-form-item {
	width: 100%;
}
.el-form-item >>> .el-form-item__content {
	width: calc(100% - 4.5rem);
}
.el-form-item__content .el-select {
	width: calc(100% - 24px);
}
.el-form-item__content .el-date-editor {
	width: calc(100% - 24px);
}
.el-form-item__content >>> .el-input {
	width: 100%;
}

.dialog-footer {
	text-align: center;
} */

.mt0 {
	margin-top: 0px;
}
.btn-footer {
	width: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
	margin-top: 20px;
}
.receiveBtn {
	float: right;
	margin-bottom: 5px;
}
.approveBg {
	position: absolute;
	top: 0px;
	right: 0px;
	width: 197px;
	height: 141px;
	background: url('../../.././assets/flight-schedule/seasonal-time-adjust-company/approveOk.png') no-repeat 0px 0px;
	background-size: 197px 141px;
}
.rejectBg {
	position: absolute;
	top: 0px;
	right: 0px;
	width: 197px;
	height: 141px;
	background: url('../../.././assets/flight-schedule/seasonal-time-adjust-company/approveReject.png') no-repeat 0px 0px;
	background-size: 197px 141px;
}

/* .el-form >>> .el-date-editor {
	width: 100%;
} */
.areaLeftClass >>> .el-textarea__inner {
	height: 80px;
}

.checkPop {
	position: absolute;
	display: flex;
	flex-direction: column;
	border: 1px solid #e6e6e6;
	background: #ffffff;
	border-radius: 4px;
	width: 100px;
	z-index: 999;
}
.checkPop .el-checkbox {
	padding: 8px 10px;
	width: 100%;
	border-bottom: 1px solid #e6e6e6;
}
.checkPop .el-checkbox:hover {
	background: #e6eaee;
}

.colRight {
	text-align: right;
}
.rightButton {
	float: right;
}

.leftForm >>> .el-form-item {
	margin-bottom: 10px;
	margin-top: 10px;
}

.reAppeal {
	z-index: 10;
}

.el-form >>> .el-form-item {
	margin-bottom: 10px;
}
.cell-add {
	color: #59b37d;
}
.cell-before {
	color: #66a0cc;
}
.cell-after {
	color: #e2a778;
}
.cell-del {
	color: #fa1919;
}

.footerDiv {
	text-align: center;
}

.mainForm >>> .el-form-item {
	margin-bottom: 0px;
}
</style>

主要el-upload,组件名LesUpload(作为子组件被引入上方代码中)

<template>
	<div>
		<!-- 文件上传 -->
		<el-upload class="avatar-uploader" :class="{ uploadDisabled: disabled }" list-type="picture-card" :action="uploadAction" :before-upload="beforeUpload" :limit="limit" :on-exceed="handleExceed" :on-success="fileUploadSuccess" :file-list="fileList" :disabled="disabled">
			<i slot="default" class="el-icon-plus"></i>
			<div slot="file" slot-scope="{ file }">
				<!-- <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" /> -->
				<span class="el-upload-list__item-actions">
					<span class="el-upload-list__item-delete" @click="handlePictureCardPreview(file)">
						<i class="el-icon-zoom-in"></i>
					</span>
					<span class="el-upload-list__item-delete" @click="handleDownload(file)">
						<i class="el-icon-download"></i>
					</span>
					<span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
						<i class="el-icon-delete"></i>
					</span>
				</span>
				<span class="fileName">{{ file.name || file.fileName }}</span>
			</div>
		</el-upload>
		<el-dialog :visible.sync="dialogVisible" append-to-body>
			<img width="100%" :src="dialogImageUrl" alt="" />
		</el-dialog>
		<iframe id="iframe" style="display: none" frameborder="0"></iframe>
	</div>
</template>

<script>
import globalFunction from '@/utils/globalFunction.js';
export default {
	name: 'LesUpload',
	props: {
		fileList: {
			type: Array,
			default() {
				return [];
			},
		},
		limit: {
			type: Number,
			default: 5,
		},
		disabled: {
			type: Boolean,
			default: false,
		},
	},
	data() {
		return {
			uploadAction: window.fileAction.uploadFileAction,
			dialogImageUrl: '',
			dialogVisible: false,

			officeFileType: ['ppt', 'pptx', 'doc', 'docx', 'xls', 'xlsx', 'csv'],
			downLoadSrc: '',
			successFileList: [],
		};
	},

	mounted() {},

	methods: {
		beforeUpload(file) {
			const isLt2M = file.size / 1024 / 1024 <= 5;
			if (!isLt2M) {
				this.$message.error('上传文件大小不能超过5MB!');
			}
			return isLt2M;
		},

		// 文件删除
		handleRemove(file) {
			this.$secondConfirm('确认删除此文件吗?').then((res) => {
				if (res) {
					this.successFileList.forEach((value, index, array) => {
						if (value.fid == file.fid) {
							array.splice(index, 1);
						}
					});
					this.$emit('onRemoveFile', file, this.successFileList);
					this.$message({
						showClose: true,
						message: '删除成功',
						type: 'success',
					});
				} else {
					this.$message({
						showClose: true,
						message: '已取消',
						type: 'info',
					});
				}
			});
		},
		handleExceed(files, fileList) {
			this.$message.warning(`当前限制选择${this.limit}个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
		},
		// 文件上传成功
		fileUploadSuccess(response, file, fileList) {
			this.successFileList = [...fileList];
			this.successFileList.pop();
			this.successFileList.push(response.data[0]);
			this.$emit('onSuccess', response, file, fileList);
		},

		// 预览
		handlePictureCardPreview(file) {
			let extendName = '';
			if (file.name) {
				extendName = file.name.substring(file.name.lastIndexOf('.') + 1);
			} else {
				extendName = file.fileName.substring(file.fileName.lastIndexOf('.') + 1);
			}

			// 若当前点击项是图片
			const PIC = ['png', 'jpg', 'jpeg', 'gif', 'svg'];
			if (PIC.includes(extendName.toLowerCase())) {
				this.dialogImageUrl = window.fileAction.fileViewAction + file.fid;
				this.dialogVisible = true;
			}
			//  若当前点击项是可以使用office在线预览的
			if ([...this.officeFileType, 'pdf'].includes(extendName.toLowerCase())) {
				globalFunction.getFileOnlineViewPathByOffice(file);
			}
			//  若当前点击项是代码或文本文件
			const CODE = ['html', 'js', 'css', 'json', 'c', 'java', 'txt'];
			if (CODE.includes(extendName.toLowerCase())) {
				window.open(globalFunction.getViewFilePath(file), '_blank');
			}
		},
		// 下载
		handleDownload(file) {
			document.getElementById('iframe').src = window.fileAction.downloadFileAction + file.fid;
		},
	},
};
</script>

<style scoped>
.avatar-uploader >>> .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	width: 80px;
	height: 80px;
	line-height: 80px;
}
.avatar-uploader >>> .el-upload:hover {
	border-color: #409eff;
}

/*el-upload上传文件*/
.avatar-uploader >>> .el-upload-list__item {
	background: url('../../assets/fileUpload/file.png') no-repeat center 10px;
	width: 80px;
	height: 80px;
	background-size: 48px 48px;
}

.avatar-uploader >>> .el-upload-list__item-name {
	width: 80px;
	position: absolute;
	left: 0px;
	bottom: 0px;
	display: block;
	font-size: 12px;
	font-family: Microsoft YaHei, Microsoft YaHei-Regular;
	font-weight: 400;
	text-align: left;
	color: #585858;
}

.avatar-uploader >>> .el-upload-list__item-name [class^='el-icon'] {
	display: none;
}
.fileName {
	width: 100%;
	font-size: 12px;
	white-space: nowrap;
	display: block;
	overflow: hidden;
	text-overflow: ellipsis;
	position: absolute;
	bottom: 0px;
	text-align: center;
}

.avatar-uploader >>> .el-upload-list--picture-card .el-upload-list__item-actions span + span {
	margin-left: 0px;
}

.avatar-uploader >>> .el-upload-list--picture-card .el-upload-list__item-actions {
	display: flex;
	justify-content: space-between;
	align-items: center;
	width: 100%;
}
.uploadDisabled >>> .el-upload--picture-card {
	display: none;
}
</style>

二、以按钮的形式上传、预览、下载文件(功能都能用)

需求:(1)点击新增按钮可以上传文件

(2)双击table某一行能够查看数据(包括上传的文件,有下载和预览功能)

(3)点击编辑,可以修改文件(就是重新上传类代码就是需求一)

父组件代码(包括新增,编辑按钮这些):

<!--
  @Author: jingtong
  @Description: 合格证书管理
  @Date: 2023-03-13 14:59:22
 * @LastEditTime: 2023-09-06 15:45:16
-->
<template>
	<el-container class="train-plan-index">
		<el-header>
			<el-row>
				<el-col :span="24">
					<el-form :inline="true" :model="form" class="demo-form-inline" ref="form">
						<el-form-item label="姓名" prop="studentName">
							<el-input v-model="form.studentName" maxlength="20"></el-input>
						</el-form-item>

						<el-form-item label="培训项目" prop="projName">
							<el-select v-model="form.projName" clearable filterable>
								<el-option v-for="item in planIdList" :key="item.uuid" :label="item.project" :value="item.project"></el-option>
							</el-select>
						</el-form-item>

						<el-form-item>
							<el-button type="primary" @click="onQuery">查询</el-button>
							<el-button @click="resetForm">重置</el-button>
						</el-form-item>
					</el-form>
				</el-col>
			</el-row>
			<el-row v-show="operateBtnShow">
				<el-col :span="24">
					<el-button type="primary" @click="addRowData">新增</el-button>
					<el-button type="primary" class="operBtn" size="small" @click="importExcel"> 导入 </el-button>
					<el-button type="primary" @click="exportRowData">导出</el-button>
					<iframe ref="exportIframe" style="display: none"></iframe>
				</el-col>
			</el-row>
		</el-header>

		<el-main>
			<el-table
				:data="tableData"
				border
				style="width: 100%"
				stripe
				height="calc(100% - 40px)"
				:default-sort="{ prop: 'saveTime', order: 'descending' }"
				@sort-change="onSortChanged"
				@row-dblclick="onTableDblclick"
				:tree-props="{children: 'children', hasChildren: 'hasChildren'}"
				row-key="uuid"
				default-expand-all
			>
				<!-- 非树状图 -->
				<!-- <el-table-column type="index" label="序号" align="center" width="60" :index="(index) => this.$common.pageIndexMethod(index, form.pageIndex, form.pageSize)"> </el-table-column>
				<el-table-column prop="studentName" label="姓名" align="center" width="150"> </el-table-column>
				<el-table-column prop="sex" label="性别" align="center" :formatter="onRendersex" width="100"> </el-table-column>
				<el-table-column prop="idCard" label="身份证号码" align="center"> </el-table-column>
				<el-table-column prop="workUnit" label="工作单位" align="center" width="150"> </el-table-column>
				<el-table-column prop="projName" label="培训项目" align="center" width="180"> </el-table-column>
				<el-table-column prop="trainId" label="培训编号" align="center"> </el-table-column>
				<el-table-column prop="certNo" label="证书编号" align="center" width="200"> </el-table-column>
				<el-table-column prop="isReceived" label="是否领取" align="center"> </el-table-column>
				<el-table-column prop="receiver" label="领取人" align="center"> </el-table-column>
				<el-table-column label="操作" align="center" width="240" v-if="operateBtnShow">
					<template slot-scope="scope">
						<el-button type="primary" @click="updateRowData(scope.row)">编辑</el-button>
						<el-button type="primary" @click="removeRowData(scope.row.uuid)">删除</el-button>
					</template>
				</el-table-column> -->

				<!-- 树状图 -->
				<el-table-column prop="projName" label="培训项目" align="center" width="180"> </el-table-column>
				<el-table-column label="参与人信息" align="center">
					<el-table-column prop="studentName" label="姓名" align="center" width="150"> </el-table-column>
					<el-table-column prop="sex" label="性别" align="center" :formatter="onRendersex" width="100"> </el-table-column>
					<el-table-column prop="idCard" label="身份证号码" align="center"> </el-table-column>
					<el-table-column prop="workUnit" label="工作单位" align="center" width="150"> </el-table-column>
					<el-table-column prop="trainId" label="培训编号" align="center"> </el-table-column>
					<el-table-column prop="certNo" label="证书编号" align="center" width="200"> </el-table-column>
					<el-table-column prop="isReceived" label="是否领取" align="center"> </el-table-column>
					<el-table-column prop="receiver" label="领取人" align="center"> </el-table-column>
				</el-table-column>
				<el-table-column label="操作" align="center" width="240" v-if="operateBtnShow">
					<template slot-scope="scope">
						<div v-if="scope.row.pid !== '0'">
							<el-button type="primary" @click="updateRowData(scope.row)">编辑</el-button>
							<el-button type="primary" @click="removeRowData(scope.row.uuid)">删除</el-button>
						</div>
					</template>
				</el-table-column> 
			</el-table>
			<pagination :total="total" :page.sync="form.pageIndex" :limit.sync="form.pageSize" @pagination="onQuery" />
		</el-main>

		<!-- 新增/编辑合格证书 -->
		<AddTrainCert :updateData.sync="selectedRow" :htmlFlag="htmlFlag" :dialogFormVisible.sync="dialogFormVisible" @handleDialogVisible="setFormVisible"></AddTrainCert>
		<!-- 导入 -->
		<ImportStudent :title="title" :templateName="templateName" :dialogFormVisible.sync="importExcelVisible" @onImportDlgClose="setImportDlgVisible"></ImportStudent>
	</el-container>
</template>
  
<script>
import pagination from '@/components/Pagination';
import AddTrainCert from '@/views/eams/trainCert/trainCert-add';
import ImportStudent from '@/views/eams/importDlg';

import { pageTrainCert, removeTrainCert, importTrainCert } from '@/api/eams/trainCert.js';
import { listBizCodeByType } from '@/api/eams/bizcode.js';
import { listTrainPlan } from '@/api/eams/trainPlan.js';

export default {
	name: 'trainCert',
	components: { pagination, AddTrainCert, ImportStudent },
	data() {
		return {
			planIdList: null,
			sexList: [],
			projNameList: [], // projNameList
			isReceivedList: [],
			form: {
				studentNo: '',
				studentName: '',
				projName: '',
				sortField: '', //排序字段
				sortOrder: '', //排序方向
				pageIndex: 0, //页数
				pageSize: 30, //每页数量
			},
			total: 0, //总数
			tableData: [],

			// 传递给子组件数据
			htmlFlag: 'add',
			selectedRow: {},
			dialogFormVisible: false, //新增合格证书窗口
			operateBtnShow: false, //证书新增、导入操作

			//导入
			file: null, //选取的导入文件
			fileList: [], //文件列表
			importExcelVisible: false, //导入弹窗
			title: '导入合格证书', //导入对话框标题
			templateName: '培训合格证书导入模板.xlsx', //模板名称
		};
	},
	mounted() {
		//教务室的人可新增、导入合格证书
		let groupName = this.$UserInfoUtil.getCurrentGroupName();
		if (groupName.indexOf('教务室') != -1) {
			this.operateBtnShow = true;
		}
		//查询性别列表
		listBizCodeByType({ type: 'sex_type' }).then((res) => {
			this.sexList = res.data.data;
		});

		//查询是否领取
		listBizCodeByType({ type: 'yes_or_no' }).then((res) => {
			this.isReceivedList = res.data.data;
		});

		listTrainPlan().then((res) => {
			this.planIdList = res.data.data;
		});

		//查询
		this.onQuery();
	},

	methods: {
		// 查询
		onQuery() {
			var param = this.getQueryCondition();
			pageTrainCert(param).then((res) => {
				//pageTrainee
				this.tableData = res.data.data ? res.data.data.data : [];
				this.tableData = this.addFatherId(this.tableData)
				this.tableData = this.toTree(this.tableData);
				this.total = res.data.data.total;
			});
		},

		//查询条件
		getQueryCondition() {
			var param = { ...this.form };
			return param;
		},

		// 重置
		resetForm() {
			this.$refs.form.resetFields();
			this.onQuery();
		},

		// 新增
		addRowData() {
			this.dialogFormVisible = true;
			this.selectedRow = {};
			this.htmlFlag = 'add';
		},

		// 修改
		updateRowData(row) {
			this.selectedRow = row;
			this.htmlFlag = 'update';
			this.dialogFormVisible = true;
		},

		// 删除数据
		removeRowData(uuid) {
			this.$confirm('确认删除该记录, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					removeTrainCert({ uuid: uuid }).then((res) => {
						if (res.data.data) {
							this.$message({
								type: 'success',
								message: '删除成功',
							});
							//刷新
							this.onQuery();
						} else {
							this.$message({
								type: 'error',
								message: '删除失败',
							});
						}
					});
				})
				.catch(() => {
					this.$message({
						type: 'success',
						message: '已取消删除',
						showClose: true,
					});
				});
		},

		//导出
		exportRowData() {
			//获取查询条件
			var vdata = this.getQueryCondition();
			// 将排序字段驼峰转大写下划线
			vdata.sortField = this.$common.toXHXUpper(vdata.sortField);
			this.$refs.exportIframe.setAttribute(
				'src',
				window.baseUrl + '/les/excel/back/export?serviceName=trainCertExport&title=' + encodeURI('合格证书导出') + '&vars=' + encodeURI(JSON.stringify(vdata))
			);
		},

		// 合格证书关闭弹窗回调
		setFormVisible(val) {
			this.dialogFormVisible = val.dialogFormVisible;
			this.onQuery();
		},

		// 导入
		importExcel() {
			this.importExcelVisible = true;
		},

		// 导入对话框关闭后回调
		setImportDlgVisible(obj) {
			this.importExcelVisible = obj.dialogFormVisible;
			this.file = obj.file;
			this.onSureImport();
		},

		//导入
		onSureImport() {
			if (!this.$common.isExcelFile(this.file.raw.type)) {
				this.$message.error('支持导入文件格式:xls、xlsx!');
				//需清空文件列表
				// this.$refs.upload.clearFiles();
				return;
			}

			var param = new FormData();
			param.append('file', this.file.raw);
			importTrainCert(param).then((res) => {
				if (res.data.data) {
					this.$message({
						type: 'success',
						message: '导入成功',
					});
					this.onQuery();
				} else {
					this.$message({
						type: 'error',
						message: '格式不正确',
					});
				}
			});

			//需清空文件列表
			// this.$refs.upload.clearFiles();
		},

		//表格排序
		onSortChanged(column) {
			var order = column.order;
			this.form.sortField = column.prop;
			this.form.sortOrder = order
				? order === 'descending' // 第一个问号:order不为空
					? 'desc'
					: 'asc'
				: '';
			this.onQuery();
		},

		//双击表格行
		onTableDblclick(row) {
			this.htmlFlag = 'look';
			this.selectedRow = row;
			this.dialogFormVisible = true;
			if(row.pid == '0'){
				this.dialogFormVisible = false;
			}
		},

		//表格渲染日期
		onRenderDate(row, column, cellValue) {
			return this.$common.parseTime(cellValue, '{y}-{m}-{d}');
		},

		//表格渲染时间
		onRenderTime(row, column, cellValue) {
			return this.$common.parseTime(cellValue, '{y}-{m}-{d} {h}:{i}');
		},

		//渲染性别
		onRendersex(row, column, cellValue) {
			return this.$common.renderCode(cellValue, this.sexList);
		},

		//渲染是否接种新冠疫苗
		onRenderisReceived(row, column, cellValue) {
			return this.$common.renderCode(cellValue, this.isReceivedList);
		},

		//渲染专业
		onRenderprojName(row, column, cellValue) {
			return this.$common.renderCode(cellValue, this.projNameList);
		},

		// 数据预处理(主要是因为没有fatherId不能转树状结构)
		addFatherId(data) {
			let map = {};
			if (!Array.isArray(data)) {
				return [];
			}
			data.forEach((item) => {
				// 如果projId是第一次出现,就给data添加节点的父元素
				if (!map[item.projId]) {
					map[item.projId] = item.projId;
					data.push({
						uuid:item.projId,
						pid:'0',
						projName: item.projName + '(' + item.trainId + ')'
					})
				}
			});
			return data;
		},
		// 数组转树形结构
		toTree(data) {
			let result = [];
			let map = {};
			if (!Array.isArray(data)) {
				//验证data是不是数组类型
				return [];
			}
			data.forEach((item) => {
				map[item.uuid] = item;
			});
			data.forEach((item) => {
				let parent = map[item.projId];
				if (parent) {
					item.projName = '';
					(parent.children || (parent.children = [])).push(item);
				} else {
					result.push(item);
				}
				});
			return result;
		},
	},
};
</script>
  
<style scoped>
.train-plan-index .el-header {
	height: auto !important;
}

.upload-plan {
	display: inline-block;
	margin: 0px 10px;
}
</style>
  
  

el-upload代码:

<template>
  <div>
    <el-dialog :title="title" class="stuinfo-add" :visible.sync="visible" @opened="openInit" @close="closeDialog" width="845px" :close-on-click-modal="false" v-el-drag-dialog>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="125px" class="demo-ruleForm" :disabled="formDisabled">
        <el-form-item label="uuid" prop="uuid" v-show="false">
          <el-input v-model="ruleForm.uuid"></el-input>
        </el-form-item>
        <el-row>
          <el-col>
            <el-form-item label="培训项目" prop="projId">
              <el-select v-model="ruleForm.projId" @change="onProjIdChanged">
                <el-option v-for="item in projIdList" :key="item.uuid" :label="item.project" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="学员" prop="studentId">
              <el-select v-model="ruleForm.studentId">
                <el-option v-for="item in studentIdList" :key="item.uuid" :label="item.studentName" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="证书编号" prop="certNo">
              <el-input v-model="ruleForm.certNo" maxlength="20"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="是否领取" prop="isReceived">
              <el-radio-group v-model="ruleForm.isReceived">
                <el-radio v-for="item in isReceivedList" :key="item.id" :label="item.id">{{ item.text }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-row>
          <el-col :span="24">
            <el-form-item label="合格证" prop="fileId">
              <el-upload ref="upload" class="upload-demo" :action="uploadPath" :on-remove="handleRemove" :before-remove="beforeRemove" multiple :limit="1" :on-exceed="handleExceed" :file-list="fileList" :auto-upload="false" :on-success="handleSuccess" :on-change="handleChange">
                <el-button size="small" type="primary" v-if="htmlFlag == 'add' || htmlFlag == 'update'">点击上传</el-button>
                <el-button size="small" type="primary" v-if="htmlFlag == 'look' || htmlFlag == 'audit'" @click="downloadFile" :disabled="false">点击下载</el-button>
                <el-button size="small" type="primary" v-if="htmlFlag == 'look' || htmlFlag == 'audit'" @click="viewCourseWare" :disabled="false">点击预览</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="领取人" prop="receiver">
              <!--学员-->
              <el-select v-model="ruleForm.receiver">
                <el-option v-for="item in studentIdList" :key="item.uuid" :label="item.studentName" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm()" v-if="htmlFlag!='look'">确定</el-button>
        <el-button @click="cancelForm()">{{htmlFlag!='look'?'取消':'关闭'}}</el-button>
      </div>
    </el-dialog>
    <!-- 文件下载的iframe -->
    <iframe :id="'downloadIframeSon' + index" style="display: none" v-for="(item, index) in downloadList" :key="'download' + index"></iframe>
    <el-dialog title="在线预览培训资料" :visible.sync="viewCoursewareVisible" class="view-dialog" append-to-body>
      <iframe style="width: 100%; height: 100%; border: none" :src="viewFileSrc1"></iframe>
    </el-dialog>
  </div>
</template>
  
<script>
import { saveTrainCert, updateTrainCert, listTrainCert } from '@/api/eams/trainCert.js';
import { listTrainPlan, listStudentByPlanId } from '@/api/eams/trainPlan.js';
import { listBizCodeByType } from '@/api/eams/bizcode.js';
let Base64 = require('js-base64').Base64;

export default {
  name: 'trainPlanData',
  props: {
    dialogFormVisible: {
      required: true,
      type: Boolean,
    },
    updateData: {
      type: Object,
      default() {
        return {};
      },
    },
    htmlFlag: {
      type: String,
      default: 'add',
    },
  },
  data() {
    return {
      title: '新增合格证书',
      studentIdList: [],
      planCourseIdList: [],
      receiverList: [],
      isReceivedList: [],
      projIdList: [],
      formDisabled: false, //表单是否禁用
      ruleForm: {
        uuid: '',
        studentId: '',
        projId: '',
        receiver: '',
        certNo: '',
        isReceived: '',
        fileId: '',
        fileName: '',
        // processInstanceId: '', //流程实例id
      },
      appealFileList:[],
      photoAction: window.fileAction.uploadFileAction,
      imageUrl: '',
      //   校验
      rules: {
        projId: [{ required: true, message: '请选择培训项目', trigger: 'change' }],
      },

      // 操作文件
      uploadPath: window.fileAction.uploadFileAction, //上传路径
      fileList: [],
      fidList: [], //上传的文件id列表
      fileNameList: [], //上传到文件名称列表
      downloadList: [], //下载列表
      viewCoursewareVisible: false, //预览附件窗口
      viewFileSrc1: '', //预览文件src
    };
  },
  computed: {
    visible: {
      get() {
        return this.dialogFormVisible;
      },
      set(val) {
        this.$emit('update:dialogFormVisible', val);
      },
    },
  },

  mounted() {
    listTrainPlan().then((res) => {
      this.projIdList = res.data.data;
    });

    listTrainCert().then((res) => {
      // POST /train/plan/listTraineeByPlanId      POST /train/plan/listStudentByPlanId
      this.receiverList = res.data.data;
    });

    //查询是否领取
    listBizCodeByType({ type: 'yes_or_no' }).then((res) => {
      this.isReceivedList = res.data.data;
    });
  },

  methods: {
    //初始化
    openInit() {
      this.closeDialog();
      this.formDisabled = false;
      if (this.htmlFlag == 'update') {
        this.title = '修改合格证书';
      } else if (this.htmlFlag == 'look') {
        this.title = '查看合格证书';
        this.formDisabled = true;
      } else if (this.htmlFlag == 'add') {
        this.title = '新增合格证书';
      }
      if (this.htmlFlag != 'add') {
        // this.ruleForm = { ...this.updateData };
        // this.ruleForm.trainTime = [this.updateData.startTime, this.updateData.endTime];
        this.imageUrl = window.fileAction.fileViewAction + this.ruleForm.photo;
        this.onProjIdChanged(this.updateData.projId, (res) => {
          this.ruleForm = { ...this.updateData };
          this.ruleForm.trainTime = [this.updateData.startTime, this.updateData.endTime];
        });
      }
      //课程资料赋值
      this.fileList = []
      if (this.updateData.fileId) {
        var fileNameList = this.updateData.fileName.split(',');
        fileNameList.forEach((item) => {
          this.fileList.push({ name: item });
        });
      }
    },

    //关闭窗口
    closeDialog() {
      // 清空表单
      this.$refs.ruleForm.resetFields();
      // 清除校验
      this.$refs.ruleForm.clearValidate();
    },

    // 触发父页面方法
    hideDialog() {
      this.$emit('handleDialogVisible', { dialogFormVisible: false });
    },

    // 提交
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          //先判断是否有附件,如果有先上传附件,然后保存或者更新成绩分析表
          if (this.ruleForm.fileId) {
            this.fileList = [this.ruleForm.fileId];
          }
          if (!this.ruleForm.fileId && this.fileList.length > 0) {
            this.submitUpload();
          } else {
            this.addOrUpdateTrainPlan();
          }
        } else {
          return false;
        }
      })
    },
    //上传至文件服务器
    submitUpload() {
      if (this.fileList.length < 0) {
        this.$message({
          type: 'warning',
          message: '请选择文件',
        });
        return;
      }
      if (this.ruleForm.fileId) {
        //原有文件,无需再次上传文件,直接提交
        //修改
        this.addOrUpdateTrainPlan({ ...this.ruleForm });
      } else {
        //新增文件,需提交文件
        this.$refs.upload.submit();
      }
    },
    //新增或修改计划
    addOrUpdateTrainPlan() {
      var param = { ...this.ruleForm };
      if (this.htmlFlag == 'add') {
        //新增
        saveTrainCert(param).then((res) => {
          if (res.data.code == '1') {
            var code = res.data.data.code;
            if (code == '1') {
              this.$message({
                type: 'success',
                message: '新增合格证书成功',
              });
              //刷新
              this.$emit('handleDialogVisible', false);
            } else {
              this.$message({
                type: 'warning',
                message: res.data.data.msg,
              });
            }

          } else {
            this.$message({
              type: 'error',
              message: '新增合格证书失败',
            })
          }
        });
      } else {
        //修改
        updateTrainCert(param).then((res) => {
          if (res.data.code == '1') {
            var code = res.data.data.code;
            if (code == '1') {
              this.$message({
                type: 'success',
                message: '修改合格证书成功',
              });
              //刷新
              this.$emit('handleDialogVisible', false);
            } else {
              this.$message({
                type: 'warning',
                message: res.data.data.msg,
              });
            }
          } else {
            this.$message({
              type: 'error',
              message: '修改合格证书失败',
            })
          }
        });
      }
    },
    // 取消
    cancelForm() {
      this.visible = false;
    },

    //培训项目值改变时
    onProjIdChanged(value, callback) {
      listStudentByPlanId({ planId: value }).then((res) => {
        var data = res.data.data;
        if (data) {
          this.studentIdList = data;
        } else {
          this.studentIdList = [];
        }
        if (callback) {
          callback();
        }
      });
    }, 

    // --------------------------------操作文件-------------------------------
    //文件移除
    handleRemove(file, fileList) {
      this.fileList = fileList;
      if (!this.fileList || this.fileList.length > 0) {
        this.$refs.ruleForm.validateField('fileId');
      }
      this.ruleForm.fileId = '';
      this.ruleForm.fileName = '';
    },
    //移除文件前
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}?`);
    },
    //定义超出限制时的行为
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件`);
    },
    //文件状态改变时的钩子
    handleChange(file, fileList) {
      this.fileList = fileList;
      if (this.fileList && this.fileList.length > 0) {
        this.$refs.ruleForm.clearValidate('fileId');
      }
    },
    //上传成功回调
    handleSuccess(response, file, fileList) {
      this.$message({
        type: 'success',
        message: '上传成功',
      })
        // 清空 fidList和fileNameList,然后添加新的 fid
        // 没有这个的话,在修改页面点击多次重新上传,查看的时候会有多个
      this.fidList = [];
      this.fileNameList = [];
      this.fidList.push(response.data[0].fid);
      this.fileNameList.push(response.data[0].name);
      console.log(this.fidList.length)
      console.log(fileList.length)
      if (this.fidList.length == fileList.length) {
        this.ruleForm.fileId = this.fidList.join(',');
        this.ruleForm.fileName = this.fileNameList.join(',');
        this.addOrUpdateTrainPlan();
      }
    },
    //下载
    downloadFile() {
      var fileId = this.updateData.fileId;
      this.downloadList = [];
      if (fileId) {
        this.downloadList = fileId.split(',');
        this.$nextTick(() => {
          this.downloadList.forEach((item, index) => {
            document.getElementById('downloadIframeSon' + index).src = window.fileAction.downloadFileAction + item;
          });
        });
      }
    },
    //预览
    viewCourseWare() {
      var row = { fileId: this.updateData.fileId, fileName: this.updateData.fileName };
      this.viewFileSrc1 = '';
      var fileIdList = row.fileId.split(',');
      var fileNameList = row.fileName.split(',');
      for (let i = 0; i < fileIdList.length; i++) {
        let url = window.fileAction.backBasePath + '/demo/' + fileNameList[i];
        this.viewCoursewareVisible = true;
        this['viewFileSrc' + (i + 1)] = window.fileAction.filePreviewAction + '?url=' + encodeURIComponent(Base64.encode(url)) + '&fid=' + fileIdList[i];
      }
    },
  },
};
</script>
  
<style scoped>
.stuinfo-add >>> .el-date-editor.el-input {
	width: 100%;
}

.stuinfo-add >>> .avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}

.stuinfo-add >>> .avatar-uploader .el-upload:hover {
	border-color: #409eff;
}

.stuinfo-add >>> .avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}

.stuinfo-add >>> .avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>







el-upload是一个Vue组件,用于实现文件上传功能。根据提供的引用内容,可以使用el-upload组件的属性和方法实现文件上传。 首先,可以设置auto-upload属性为false,取消自动上传功能。这样,在选中文件后,文件不会自动上传。然后,在按钮的点击事件中,使用DOM调用submit方法手动上传文件。\[1\] 另一种实现方式是,在点击确定按钮时,创建一个formData对象,并遍历选中的文件列表,使用append方法将文件添加到formData中。最后,调用uploadFiles函数,将formData作为参数传递给axios的post方法实现文件上传。\[2\] 还可以使用http-request属性来自定义上传请求的行为。在httpRequest函数中,可以获取到选中的文件对象,然后创建一个formData对象,并将文件添加到formData中。最后,使用axios的post方法将formData发送到服务器进行文件上传。\[3\] 综上所述,el-upload组件可以通过设置auto-upload属性、使用submit方法或自定义http-request函数来实现文件上传功能。 #### 引用[.reference_title] - *1* *2* *3* [el-upload上传文件](https://blog.csdn.net/chilanzi/article/details/125200573)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值