Uni-App开发微信小程序获取用户头像和用户昵称

1,064 阅读1分钟

前言

微信小程序获取用户头像昵称的API经过调整之后不能再通过getUserPofile接口获取(获取到的是灰色头像和默认昵称),转而使用组件的type属性获取。

使用案例

头像

这里通过button 里的open-type="chooseAvatar"获取用户头像,然后通过 onChooseAvatar 事件并传入的参数e,获取本地头像的链接e.detail.avatarUrl,然后将该链接通过uni.uploadFile上传,

PS:需要注意的是如果使用了Popup之类的弹框组件,需要在函数最后依然控制showProps的打开状态,因为如果选择了上传相册图片作为头像会导致弹框消失

昵称

昵称则通过input的type="nickname" 属性获取, 通过v-model绑定即可。

PS:在编译器和手机预览时直接从该input获取的用户昵称会在双向数据绑定时为空,在实机调试模式时则正常。

不得不吐槽微信小程序的问题真多....

代码演示:

<template>
  <nut-popup
    :close-on-click-overlay="true"
    :custom-style="{ padding: '0px 0px', borderRadius: '12px' }"
    v-model:visible="showName"
  >
    <view class="getPhoneNumber" style="height: 40vh;">
      <h1 class="getPhoneNumber-title">完善用户信息</h1>
      <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
        <image v-if="avatarUrl==null" style="width: 50%;margin: auto;" src="../../static/images/user/user.svg" />
        <image v-else class="avatar" :src="avatarUrl"></image>
      </button>
      <nut-form-item label="昵称">
        <input style="color: #000;" type="nickname" v-model="nickName" class="weui-input" placeholder="请输入昵称" />
      </nut-form-item>
      <view class="but">
        <button class="sumbit" @click="submitAvatar()">提交</button>
      </view>
    </view>
  </nut-popup>
</template>

<script>
export default {
  data() {
    return {
      showName: false,
      avatarUrl: null,
      nickName: ''
    }
  },
  methods: {
    onChooseAvatar(e) {
      console.log(e);
      this.avatarUrl = e.detail.avatarUrl;
    },
    submitAvatar() {
      if (!this.avatarUrl || !this.nickName) {
        console.error('请填写完整信息');
        return;
      }
      const token = getToken();
      uni.uploadFile({
        url: url,
        filePath: this.avatarUrl,
        name: 'file',
        success: (res) => {
          const data = JSON.parse(res.data);
          console.log('res', data);
          this.hash = data.data.hash;
          this.showName = true;
          // 关闭弹框
          // this.$emit('closePopup'); // 如果是组件内部的弹框
        },
        fail: (err) => {
          console.error('上传失败', err);
          // 处理上传失败的情况
        }
      });
    }
  }
}
</script>

效果演示