官方给的方法
需要将 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){ //错误 } },
我是用的本地覆盖储存方法 具体看你们怎么写了