<img :src="upImg" alt=""> //属性绑定为upImg在data()中声名
<input class="lost" type="file" id="file" @change="upLoadImg($event)" ref="file">
复制代码
属性有点多由于我这个是vue的项目因此有用到ref,jq的话就能够直接用id 来查找元素进行事件的绑定和更改vue
upLoadImg(e) {
let that = e.target //保存当前的input元素
let fr = new FileReader() //初始化
fr.readAsDataURL(e.target.files[0]) //选择文件中的头一个开始读取,将img读取为base64编码能够被img直接解析
fr.onload = e => { //在filereader中读取完毕开始异步加载
this.upImg = e.target.result
that.value = null //解决change事件重复选择同一文件是不能从新渲染载入事件
}
}
复制代码
这样fileReader就将img读取为base64的编码,这个跟在初始化vue项目后在本地加载图片是想要直接在img标签中引用,是须要在script中进行require就是将其转化为base64的编码再有vue渲染到img的src中的.bash
<span @click="upLoadClick($event)" class="upload">
哪里不会点这里
<input class="lost" type="file" id="file" @change="upLoadImg($event)" ref="file">
</span>
<script>
upLoadClick(e) {
e.click = this.$refs.file.click()
console.log(this.$refs);
},
</script>
<style lang='stylus' scoped>
.lost //stylus 就是这么省略...
display none
</style>
复制代码
这样将input file的点击事件帮给了 .upload异步
这样咱们就能够愉快的上传了,去试试,能够作到图片预览了没,最后仍是最好把图片的样式给规定下,太大的站位会影响总体布局的.布局