前言
upload上传组件提供了很多种案例,这次列举的是`图片列表缩略图`的上传
1. on-preview 点击文件列表中已上传的文件时的钩子 function(file)
2. on-remove 文件列表移除文件时的钩子 function(file, fileList)
3. on-success 文件上传成功时的钩子 function(response, file, fileList)
上传图片代码
由于我们进行图片上传需要请求接口(需要携带token),这时候直接使用action是不可以的,我们可以使用http-request="httpRequest"去覆盖默认的action提交的数据
<template>
<el-upload
ref="upload"
action=""
:on-preview="handlePreview"
:on-success="success"
:http-request="httpRequest"
:file-list="fileList"
list-type="picture"
:on-remove="handleRemove"
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
上传图片完成之后预览图片代码
<!-- 图片预览窗口 -->
<el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
<img :src="previewPath" class="previewImg" />
</el-dialog>
<script>
export default {
data() {
return {
fileList: [], //存取图片的路径
//控制图片预览窗口的显示与隐藏
previewVisible: false,
//图片地址
previewPath: '',
}
}
}
- 用到的方法
methods:{
//触发图片预览
handlePreview(file){
this.previewVisible = true;
this.previewPath = file.response.url;
},
//点击删除图片
handleRemove(file){ //file是将要移除的那个图片的信息,可以console.log(file),查看file有什么信息
//1.获取将要删除的图片的临时路径
const filePath = file.response.data.tmp_path;
//2.从pics数组中找到图片对应的索引值
//形参‘x’,是数组pic里的每一项
const i = this.addForm.pics.findIndex(x =>
x.pic == filePath);
//调用数组的splice方法,把图片的信息对象从pics数组中移除
this.addForm.pics.splice(i,1);
this.$message.success("图片删除成功!");
},
//监听图片上传成功
success(e) {
//将图片信息对象,push到pics数组中
this.ruleForm.pics.push({ pic: e.tmp_path })
//console.log(this.addForm)
},
//调用接口传图片的上传路径
async httpRequest(param) {
let formData = new FormData() // FormData 对象
formData.append('file', param.file) // 文件对象
let data = await photo(formData).catch((err) => {
console.error(err)
})
return data
},
}