<el-upload
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-success='success'
:file-list="fileList"
:headers="uploadHead"
action="http://localhost:8888/api/private/v1/upload"
list-type="picture">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
<script>
export default {
data () {
return {
// 上传商品图片
fileList: [],
uploadHead: {
Authorization: localStorage.getItem('token')
}, // 由于用的是element-ui中的组件 不能用自己的方法提交 所以使用组件中的方法 设置请求头
// 图片预览
dialogImg: false,
}
},
methods: {
// 6.图片上传成功时
success (res, file, fileList) {
// 将上传成功的图片保存到 fileList 中
// res: 服务器响应回来的数据
// tmp_path: 生成的图片的名称
// url: 上传后图片所在的服务器的路径
// file: 本次上传文件信息(包含了 res)
// fileList: 上传的所有文件信息(包含了 file)
console.log(file)
// console.log(fileList);
this.fileList.push({
name: res.data.tmp_path,
url: res.data.url
})
},
// 7.删除图片时
handleRemove (file, fileList) {
// console.log(file);
// console.log(fileList);
// 通过file中的属性删除信息
for (var i = 0; i < this.fileList.length; i++) {
if (this.fileList[i].name === file.name) {
this.fileList.splice(i, 1)
}
}
},
// 8.图片预览
handlePreview (file) {
// console.log(file);
this.dialogImg = true
// 解决方法:1)将 src 中的图片数据放到 data 中
// 2)等页面重新渲染时我们才执行这个 dome 操作
// this.$refs.myimg.src= file.url 这种方法行不通,因为当代码从上到下执行完时事件已经被注册, 没有
this.$nextTick(function () {
this.$refs.myimg.src = file.url
})
},
}
}
</script>
简单的图片上传功能
最新推荐文章于 2024-03-27 15:19:47 发布