头像上传替换url不刷新

2019-06-29  本文已影响0人  小俊的世界

最近再做师资头像上传   发现利用el-upload  这里面的一个事件  file-change 这个事件中的file对象是有一个url的

原本以为 将src = file.url 之后便是可以的   结果发现并不能成功   

数据改变  视图并不刷新

解决:利用  this.$forceupdate()  强制更新

具体代码:

html片断:

action=""

:show-file-list="false"

:http-request="uploadFun"

:on-change="fileChange"

:before-upload="beforeAvatarUpload">

width="80"

height="80"

:src="photoUrl"

class="avatar">

class="el-icon-plus avatar-uploader-icon">

js:

图片格式的处理:

beforeAvatarUpload(file) {

const isImage = (file.type === 'image/jpeg' || file.type === 'image/png')

if (!isImage) {

this.$message.error('上传头像必须为png,jpg格式的图片!')

}

return isImage

}

上传替换原有图片的url:

fileChange(file) {

this.photoFile = file.raw

this.photoUrl = file.url

this.$forceUpdate()

},

还可以利用base64的方式注入到src中的

const reader = new FileReader()

reader.readAsDataURL(file.raw)

reader.onload = (e) => {

this.photoUrl = reader.result

this.$forceUpdate()      同样需要强制刷新

}

上一篇 下一篇

猜你喜欢

热点阅读