<div id="avatarContainer">
<el-avatar :src="form.pic" size="large" id="avatar"></el-avatar>
<el-button type="primary" round size="small" @click="changeFile" id="changePicBtn">修改</el-button>
<input type="file" id="inputFile" ref="inputFile" accept="image/gif,image/jpeg,image/jpg,image/png" style="display:none;"/>
</div>
changeFile(){
let fileInput = this.$refs.inputFile;
fileInput.click();//点击弹出选择框
//文件域文件改变
fileInput.addEventListener('change',this.readFile);
},
readFile(){
//获取文件域元素
let fileInput = this.$refs.inputFile;
let that = this;
//获取上传的图片
let file = fileInput.files[0];
//准备读取图片
if (window.FileReader && file) {
//调用图片读取方法
var reader = new FileReader();
//读取图片
reader.readAsDataURL(file);
//监听图片读取进度
reader.onloadend = function(e) {
//读取成功,拿到base64编码
let imgBase64 = e.target.result;
that.picBase64 = imgBase64;//便于保存操作使用
that.form.pic = imgBase64;//更改页面上的头像
that.$message('头像已选择');
//移除change事件
fileInput.removeEventListener('change',that.readFile);
//解决文件域再次选择同一个文件时不触发change事件
document.getElementById('inputFile').value = '';
}
}
},

至此欧了!
该代码段展示了如何在Vue.js中使用el-avatar组件结合FileReaderAPI实现头像选择功能,读取图片为Base64编码,并更新页面显示。

5649

被折叠的 条评论
为什么被折叠?



