vue 更改頭像功能實現


 ——————– 
如上圖所示:需要完成的功能是點擊更改頭像,獲取本地文件庫,選擇圖片后將原始圖片替換。這里我就直接用html文件引入vue來簡單實現在這功能,代碼如下: 
HTML:

<div id="app"> <div class="item_bock head_p"> <div class="head_img"> <img :src="userInfo.avatar"/> <--圖片地址動態綁定--> </div> <div class="setting_right" @click.stop="uploadHeadImg"> <div class="caption">更改頭像</div> </div> <input type="file" accept="image/*" @change="handleFile" class="hiddenInput"/> </div> </div>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

注意: 
1.accept 屬性用於限制圖像的格式 如:(accept=”image/gif, image/jpeg”),accept=”image/*”表示不限制格式。 
2.真正打開本地文件的是input,但這里是將其隱藏的。

JS:

var app = new Vue({ el: '#app', data: { userInfo: { avatar: 'https://gss0.bdstatic.com/-4o3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=62d46c39067b020818c437b303b099b6/d4628535e5dde7119c3d076aabefce1b9c1661ba.jpg' } // 初始圖片 }, methods: { // 打開圖片上傳 uploadHeadImg: function () { this.$el.querySelector('.hiddenInput').click() }, // 將頭像顯示 handleFile: function (e) { let $target = e.target || e.srcElement let file = $target.files[0] var reader = new FileReader() reader.onload = (data) => { let res = data.target || data.srcElement this.userInfo.avatar = res.result } reader.readAsDataURL(file) }, } })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

注意: 
1.this.$el.querySelector('.hiddenInput') 是獲取文檔中 class=”hiddenInput” 的元素。 
2.在打開文件夾選中圖片確認后,執行handleFile函數 
3.let $target = e.target || e.srcElement 表示調用他的各種屬性, 
兩個的區別是:ie下支持e.srcElement,ff支持e.target。 
4.由於手機上可以選擇多張圖片,所以let file = $target.files[0],表示取第一張圖。 
5.var reader = new FileReader() FileReader 對象允許Web應用程序異步讀取存儲在用戶計算機上的文件(或原始數據緩沖區)的內容,使用 File 或 Blob 對象指定要讀取的文件或數據。 
6.onload 事件會在頁面或圖像加載完成后立即發生。 
7.FileReader對象的readAsDataURL方法可以將讀取到的文件編碼成Data URL。

css:

.item_bock { display: flex; align-items: center; justify-content: space-between; height:94px; width: 300px; padding:0px 24px 0px 38px; border-bottom: 1px solid #f7f7f7; background: #fff; } .head_p { height:132px; } .head_img{ height: 90px; } .head_img img{ width:90px; height:90px; border-radius:50px } .setting_right{ display: flex; height: 37px; justify-content: flex-end; align-items: center; } .hiddenInput{ display: none; } .caption { color: #8F8F8F; font-size: 26px; height: 37px; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

這里只是將圖片顯示出來,並沒有保存起來,如果需要上傳或者保存,需要后台接口配合。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM