使用Element的upload上传组件,不使用action属性上传
action属性值为"#"
增加了:http-request="httpRequest"方法
解释:
http-request 覆盖默认的上传行为,可以自定义上传的实现
<template>
<div>
<el-upload
class
=
"avatar-uploader"
action=
"#"
:http-request=
"httpRequest"
:show-file-list=
"false"
:before-upload=
"beforeAvatarUpload"
>
<img v-
if
=
"data.imageUrl"
:src=
"data.imageUrl"
class
=
"avatar"
>
<i v-
else
class
=
"el-icon-plus avatar-uploader-icon"
></i>
</el-upload>
<div
class
=
"content"
>
<p>
<span>文章标题</span>
<el-input v-model=
"data.title"
placeholder=
"文章标题"
></el-input>
</p>
<p>
<span>文章简介</span>
<el-input v-model=
"data.summary"
placeholder=
"文章简介"
></el-input>
</p>
<p>
<span>文章内容</span>
<el-input v-model=
"data.content"
placeholder=
"文章内容"
></el-input>
</p>
<p>
<el-button type=
"primary"
@click=
"onSubmit"
class
=
"submitButton"
>提交</el-button>
</p>
</div>
</div>
</template>
js相关代码
httpRequest方法主要处理显示缩略图,并且将需要用到的file转换成base64的文件格式
export
default
{
data () {
return
{
data: {
title:
''
,
summary:
''
,
content:
''
,
imageUrl:
''
}
}
},
methods: {
// 上传之前的格式设置
beforeAvatarUpload (file) {
const isJPG = file.type ===
'image/jpeg'
const isLt2M = file.size / 1024 / 1024 < 2
if
(!isJPG) {
this
.$message.error(
'上传头像图片只能是 JPG 格式!'
)
}
if
(!isLt2M) {
this
.$message.error(
'上传头像图片大小不能超过 2MB!'
)
}
return
isJPG && isLt2M
},
httpRequest (data) {
let
_this =
this
let
rd =
new
FileReader()
// 创建文件读取对象
let
file = data.file
rd.readAsDataURL(file)
// 文件读取装换为base64类型
rd.onloadend =
function
(e) {
_this.data.imageUrl =
this
.result
// this指向当前方法onloadend的作用域
}
},
onSubmit () {
console.log(
this
.data)
console.log(
'submit!'
)
}
}
}
</script>
更多推荐
所有评论(0)