element 的的引入不用说了吧
axios的封装跟使用本人博客有详细介绍
https://blog.youkuaiyun.com/qq_45970524/article/details/114264507
直接撸代码
<template>
<div>
<el-upload
class="upload-demo"
ref="upload"
action="#"
:limit="1"
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-change="handleChange"
:file-list="fileList"
:auto-upload="false"
>
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button
style="margin-left: 10px"
size="small"
type="success"
@click="submitUpload"
>上传到服务器</el-button
>
<div
slot="tip"
class="el-upload__tip"
style="color: #f56c6c"
>
<i class="el-icon-warning"></i> 提示:只能选取单个文件
</div>
</el-upload>
</div>
</template>
<script>
// upload 是文件上传的接口地址
import { upload } from "@/api/upload/upload";
export default {
data() {
return {
fileList: [],
};
},
methods: {
// 文件上传
submitUpload() {
var formData = new FormData();
for (var index = 0; index < this.fileList.length; index++) {
formData.append("file", this.fileList[index].raw);
}
upload(formData).then((response) => {
if (response.code == 200) {
this.msgSuccess("文件上传成功");
this.fileList = [];
}
});
},
// 文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
handleChange(file, fileList) {
this.fileList = fileList;
},
// 文件列表移除文件时的钩子
handleRemove(file, fileList) {},
// 点击文件列表中已上传的文件时的钩子
handlePreview(file) {},
},
watch: {},
mounted() {},
created() {},
beforeDestroy() {},
};
</script>