在upload组件里面上传图片之后 不显示
<el-upload
class="avatar-uploader"
action="https://jsonplaceholder.typicode.com/posts/"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<style></style>
<script>
export default {
data() {
return {
imageUrl: ''
};
},
methods: {
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
},
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;
}
}
}
</script>
这个问题的原因是因为 upload组件的有一个自动上的属性auto-upload默认值是true,也就是说当用户选择图片之后就会立即上传。这时如果上传地址接口有问题的话就会到时 上传不成功没有办法触发handleAvatarSuccess这个钩子函数。导致没有渲染出图片。
- 解决
在项目中 一般都是用户点击按钮之后才会进行 往后台数据库插入的操作
所以我们一般会把 auto-upload属性设置成false,通过组件的submit()方法来提交文件
为了解决这个问题 我们就需要在其他的钩子函数里 来触发给渲染图片的区域赋值图片的地址、
我们可以在 on-change这个钩子函数里面来做这个事情 this.imageUrl=URL.createObjectURL(file.raw);
<el-upload
class="avatar-uploader"
action="https://jsonplaceholder.typicode.com/posts/"
:show-file-list="false"
:on-change="handleAvatarChange" //文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
handleAvatarChange(file,filelist){
this.imageUrl=URL.createObjectURL(file.raw);
}
然后我们在每次打开弹窗时、清除掉图片的地址就好了 this.imageUrl=“”
- 可能有更好的解决方法 希望大家多多交流