<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異步
這樣咱們就能夠愉快的上傳了,去試試,能夠作到圖片預覽了沒,最後仍是最好把圖片的樣式給規定下,太大的站位會影響總體佈局的.佈局