From表单中实现图片上传功能(前端上传)vue+element UI
一、实现效果
初始状态有一张默认图片,鼠标移入,显示“点击上传”,点击上传一张新的图片替换前一张图片,并获取信息。
二、实现代码
1、HTML部分
<label type="button" @mouseover="() => {imgShow = true}" @mouseout="() => {imgShow = false}">
<div :class="imgShow?'avatar imgWord':'avatar imgWord imgWord2'"> 点击上传 / 修改 </div>
<img :src="imageUrl" alt="" class="avatar">
<el-upload v-show="false" ref="upload" action="" list-type="picture-card" :before-
upload="beforeAvatarUpload">
<i slot="default" class="el-icon-plus defaultPlus"></i>
</el-upload>
</label>
2、JS部分
export default {
components: {},
props: {},
data () {
return {
imgShow: false,
imageUrl: require('@/assets/img/code.svg'),
}
},
methods: {
beforeAvatarUpload (file) {
const a = new FileReader()
a.readAsDataURL(file)
a.onload = (e) => {
let base64 = e.target.result
this.form.mpQr = base64
this.imageUrl = base64
}
}
}
}
3、CSS部分
.imgWord {
position: absolute;
color: #000;
font-size: 17px;
font-weight: 800;
line-height: 40px;
text-align: center;
display: block;
background: rgba(255, 255, 255, 0.7);
}
.imgWord2 {
display: none;
}
.avatar:hover {
cursor: pointer;
}
|