- 隐藏input输入框使用$refs获取dom并且触发点击事件
<p @click="$refs.file.click()">点击修改头像</p>
<input type="file" hidden ref='file' @change="onFileChange">
dialogVisible值为true时弹出对话框
<!-- Dialog 上传头像对话框 -->
<el-dialog
append-to-body
title="提示"
:visible.sync="dialogVisible"
width="30%"
>
<!-- src绑定处理后的图片路径 -->
<img :src="previewImage" width="150px">
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="dialogVisible = false">确 定</el-button>
</span>
</el-dialog>
<!-- Dialog 上传头像对话框 -->
data() {
return {
previewImage:'',//处理后的图片路径
dialogVisible: false,//控制上传头像对话框
}
}
- input的change事件
获取文件并处理文件路径赋值给previewImage
展示弹出层,预览用户选择图片
处理选择相同文件不触发change事件,把input中的value设置为空
onFileChange(){
// 处理预览图片
const file=this.$refs.file
// URL.createObjectURL()方法会根据传入的参数创建一个指向该参数对象的URL
const blobData=window.URL.createObjectURL(file.files[0])
// console.log(blobData)
// 将地址赋值给previewImage
this.previewImage=blobData
// 展示弹出层,预览用户选择图片
this.dialogVisible=true
// 解决选择相同文件不触发change事件问题
this.$refs.file.value=''
}