vue2项目中要求实现图片上传,elementUI为我们提供了便捷的图片上传组件,接下来以组件中照片墙为例简单介绍<el-upload>组件使用:
献上官网链接:Element - The world's most popular Vue UI framework
一、代码展示
<template>
<div class="image_upload">
<el-upload
:action="url"
list-type="picture-card"
:on-success="imageSuccess"
:on-remove="changeUpload"
:on-exceed="handleExceed"
:limit="2"
multiple
>
<i class="el-icon-plus"></i>
</el-upload>
<div v-if="isShow" slot="tip" class="el-upload__tip">
只能上传jpg/png文件,最多只能上传2个图片
</div>
</div>
</template>
<script>
import { mapState } from 'vuex'
import { upload, host } from '@/api/base'
export default {
name: 'imageUpload',
data() {
return {
url: upload,
isShow: false,
}
},
methods: {
// 图片预览
imagePreview(file) {
console.log(file)
},
// 图片删除
handleRemove(file) {
console.log(file)
},
// 图片上传成功回调函数
imageSuccess(response, file, fileList) {
// 获取图片上传后的地址
const url = response.url.slice(7)
const imageUrl = `${host}/${url}`
console.log(imageUrl)
this.goodsForm.image = imageUrl
},
// 文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
changeUpload() {
this.isShow = false
},
// 文件超出个数限制时的钩子
handleExceed(files, fileList) {
console.log(files, fileList)
this.isShow = true
},
},
computed: {
...mapState('goodsList', ['goodsForm']),
},
}
</script>
<style lang="less" scoped>
.el-upload__tip {
color: red;
}
</style>
代码中,当图片上传成功后,需要获取图片上传后的地址。这里用到拼接 const imageUrl = `${host}/${url}`
host指的是export const host = 'http://localhost:9898'
url指的是下面图片框出的路径中第八个开始取完,用到String.prototype.slice()方法
const url = response.url.slice(7)
然后一拼接 const imageUrl = `${host}/${url}` 得到完整的上传图片路径。
二、组件解读
1.属性解读
action:必选参数,上传的地址。 :action='url'
list-type:文件列表的类型 text / picture / picture-card
text类型:
picture类型:
picture-card类型
on-preview:点击文件列表中已上传的文件时的钩子 function(file)
on-remove:文件列表移除文件时的钩子 function(file, fileList)
on-success:文件上传成功时候的钩子 function(response, file, fileList)
on-error:文件上传失败的钩子 function(err, file, fileList)
on-change:文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
function(file, fileList)
auto-upload:是否在选取文件后立即进行上传 boolean
limit:最大允许上传个数 number
on-exceed:文件超出个数限制时的钩子 function(files, fileList)
tips:文件超出个数可通过limit的值作为判断依据
multiple:是否支持多选文件 boolean
file-list:上传多个文件列表数据 array
2.函数参数解读
response:图片信息(图片名称、url)
file:文件信息
fileList :多图片文件上传列表
简单罗列一些,后续会持续更新~~~