**前言**
upload上传组件提供了很多种案例,这次列举的是`图片列表缩略图`的上传
1. on-preview 点击文件列表中已上传的文件时的钩子 function(file)
2. on-remove 文件列表移除文件时的钩子 function(file, fileList)
3. on-success 文件上传成功时的钩子 function(response, file, fileList)
add.vue
<template>
<!-- 图片上传 -->
<!-- action:表示图片要上传到的后台API地址 -->
<!-- :on-preview->点击触发图片预览 -->
<!-- list-type:上传的东西要呈现的形式 -->
<el-upload
action="http://127.0.0.1:8888/api/private/v1/upload"
:on-preview="handlePreview" //实现图片预览
:on-remove="handleRemove" //点击删除图片
list-type="picture"
:headers="headerObj" //设置上传的请求头部
:on-success="handleSuccess" //监听图片上传成功
>
<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{
//图片上传组件的headers请求头对象
headerObj:{
Authorization:window.sessionStorage.getItem('token')
},
//控制图片预览窗口的显示与隐藏
previewVisible:false,
//图片地址
previewPath:'',
}
}
}
- 用到的方法
methods:{
//触发图片预览
handlePreview(file){
this.previewVisible = true;
this.previewPath = file.response.data.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("图片删除成功!");
},
//监听图片上传成功
handleSuccess(response){
//拼接得到图片信息对象
const picInfo = {
pic:response.data.tmp_path};
//将图片信息对象,push到pics数组中
this.addForm.pics.push(picInfo);
//console.log(this.addForm)
}
}