官方給的方法
需要將 button 組件open-type
的值設置為chooseAvatar
,當用戶選擇需要使用的頭像之后,可以通過bindchooseavatar
事件回調獲取到獲取到頭像信息的臨時路徑。
<button class="avatar-wrapper" open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar"> <image class="avatar" src="{{avatarUrl}}"></image> </button> const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0' Page({ data: { avatarUrl: defaultAvatarUrl, }, onChooseAvatar(e) { const { avatarUrl } = e.detail this.setData({ avatarUrl, }) } })
這個方法可以解決 但是必須要用戶點擊授權微信頭像才可以 而且頭像路徑是臨時的 跳轉別的頁面或者刷新之后就會消失
倆方法解決 一個是發布服務器或者雲端儲存 一個是本地覆蓋儲存 上述替代方法可以做到獲取用戶微信頭像 或者本地相冊頭像 或拍照 特別好用
下邊是我寫uniapp的代碼:
template 里邊的代碼 <button class="user_img" open-type="chooseAvatar" @chooseavatar="onChooseAvatar"> <image class="user_imgurl" :src="avatarUrl"></image> </button> data定義的默認頭像 灰色頭像 avatarUrl : 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0' methods 里邊的代碼 //獲取頭像 onChooseAvatar(e) { console.log("頭像=====",e) this.avatarUrl = e.detail.avatarUrl // console.log(this.avatarUrl) try{ uni.setStorageSync('img_Url', e.detail.avatarUrl) } catch (e){ //錯誤 } }, 本地儲存 下次進入自動獲取mounted() { try { const value = uni.getStorageSync("img_Url"); if(value) { console.log(value) this.avatarUrl = value } } catch(e){ //錯誤 } },
我是用的本地覆蓋儲存方法 具體看你們怎么寫了