小程序 获取用户头像、昵称、手机号的组件封装(最新版)

在父组件引入该组件

javascript 复制代码
<!-- 授权信息 -->
  <auth-mes showModal="{{showModal}}" id='autnMes' bind:onConfirm="onConfirm"></auth-mes>

子组件详细代码为:

authMes.wxml

html 复制代码
<!-- components/authMes/authMes.wxml -->
<van-popup show="{{ showModal }}" round bind:close="closeHandle" custom-class="auth-box" custom-style="width: 84%;z-index:10002;" overlay-style="z-index:10001;">
  <view class="auth-wrap">
    <view>
      <view class="tips-tit">提示</view>
      <view class="tips-txt">为提供更好的服务,我们邀请您填写昵称,头像等公开信息</view>
    </view>
    <view class="auth-cont">
      <view class="auth-itm">
        <view class="itm-tit">头像</view>
        <view class="avatar-cont">
          <button class="avatar-btn" open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar">
            <image class="avatar" src="{{avatarMes.avatarUrl}}" wx:if="{{avatarMes.avatarUrl}}"></image>
            <image class="avatar" src="../../images/common/auth_default.png" wx:if="{{!avatarMes.avatarUrl}}"></image>
            <image class="icon-r" src="../../images/common/icon_arrow_black.png" />
          </button>
        </view>
      </view>
      <view class="auth-itm">
        <view class="itm-tit">昵称</view>
        <input class="nick-name" placeholder="点击输入" type="nickname" value="{{avatarMes.nickName}}" bindblur="bindblur" placeholder-class="input-holder"></input>
      </view>
      <view class="auth-itm">
        <view class="itm-tit">手机号</view>
        <view>
          <button slot="button" plain size="mini" type="" open-type="getPhoneNumber" bindgetphonenumber="getPhone" class="phone-btn">
            <text wx:if="{{!avatarMes.mobile}}">获取手机号</text>
            <text wx:if="{{avatarMes.mobile}}" style="color:#302e2d;">{{avatarMes.mobile}}</text>
          </button>
        </view>
      </view>
    </view>
    <view class="auth-btn">
      <view class="btn" catchtap="cancel">取消</view>
      <view class="btn com-btn" catchtap="confirm">确认</view>
    </view>
  </view>
</van-popup>

authMes.js

javascript 复制代码
// components/authMes/authMes.js
// 获取应用实例
const app = getApp();
const { enums } = require("../../common/config/enums");
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 小程序弹窗
    showModal: {
      type: Boolean,
      value: false,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    avatarMes: {
      avatarUrl: "",
      nickName: "",
      mobile: "",
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /** 获取昵称信息 */
    bindblur(res) {
      const value = res.detail.value;
      this.data.avatarMes.nickName = value;
    },
    // 拿到头像信息的临时路径
    onChooseAvatar(e) {
      const { avatarUrl } = e.detail;
      console.log('ddd', avatarUrl);
      this.uploadAva(e.detail.avatarUrl);
    },
    uploadAva(tempFilePaths) {
      var that = this;
      wx.uploadFile({
        url: app.siteinfo.apiUrl + '图片上传接口', //需要用HTTPS,同时在微信公众平台后台添加服务器地址
        filePath: tempFilePaths, //上传的文件本地地址
        name: "Image", //服务器定义的Key值
        header: {
          'content-type': 'multipart/form-data',
          'cookie': wx.getStorageSync('cookie')
        },
        formData: {
          //接口所需的其他上传字段
          uploadDir: enums.UploadDir.Personal.Value,
          fileType: enums.FileType.Image.Value,
        },
        // 附近数据,这里为路径
        success: function (res) {
          wx.hideLoading();
          if (res.statusCode == 200) {
            var result = JSON.parse(res.data);
            if (result.status) {
              // var imgUrl = [{ name: 'headImgUrl', url: result.data.fileurl }];
              that.setData({
                'avatarMes.avatarUrl': result.data.fileurl
              })
            } else {
              app.alert.show(res.errmsg);
            }
          } else {
            app.alert.show(res);
          }
        },
        fail: function (err) {
          console.log(err);
        }
      });
    },
    // 输入
    onChange(e) {
      let field = 'avatarMes.' + e.currentTarget.dataset.field;
      this.setData({
        [field]: e.detail
      });
    },
    // 手机号授权
    getPhone(mobile) {
      console.log('mobile.detail', mobile.detail)
      if (mobile.detail && mobile.detail.code) {
        let code = mobile.detail.code;
        app.apis('手机号解码接口', { code: code }).then(res => {
          if (res.status) {
            this.setData({
              'avatarMes.mobile': res.data.Mobile
            });
          } else {
            app.alert.show('获取手机号码失败,请重试!' + res.errmsg);
          }
        })
      } else {
        app.toast.show(mobile.detail.errMsg);
      }
    },
    //点击遮罩层关闭
    closeHandle() {
      this.setData({
        showModal: false
      })
    },
    // 取消
    cancel() {
      this.setData({
        showModal: false
      })
    },
    // 确认
    confirm() {
      this.triggerEvent('onConfirm', { avatar: this.data.avatarMes });
    },
  },
})

authMes.less

css 复制代码
.auth-wrap {
  border-radius: 40rpx;
  box-sizing: border-box;
  padding: 24rpx;
  opacity: 1;
  background-color: #ffffff;
  z-index: 100002;
  .tips-tit {
    font-family: PingFangSC-Medium;
    font-size: 32rpx;
    color: #302e2d;
    text-align: center;
    font-weight: 500;
  }
  .tips-txt {
    padding: 40rpx 10rpx;
    font-size: 28rpx;
    color: #282b34;
    letter-spacing: 0;
    text-align: center;
    font-weight: 400;
  }
  .auth-cont {
    .auth-itm {
      background-color: #f6f6f6;
      border-radius: 20rpx;
      padding: 0 24rpx;
      height: 96rpx;
      margin-bottom: 24rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .itm-tit {
        width: 100rpx;
        font-family: PingFangSC-Regular;
        font-size: 28rpx;
        color: #302e2d;
      }

      .avatar-cont {
        width: 18%;
        .avatar-btn {
          width: 100%;
          height: 96rpx;
          padding: 0!important;
          box-sizing: content-box !important;
          background-color: transparent;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .avatar {
            width: 56rpx;
            height: 56rpx;
            display: inline-block;
          }
          &::after {
            border: none;
          }
        }
        .icon-r {
          width: 24rpx;
          height: 24rpx;
          margin-left: 8rpx;
        }
      }
      .nick-name {
        text-align: right;
        font-family: PingFangSC-Regular;
        font-size: 28rpx;
        color: #302e2d;
      }
    }
  }
  .aggre-v {
    display: flex;
    align-items: center;
    font-family: PingFangSC-Regular;
    font-size: 26rpx;
    color: #302e2d;
    font-weight: 400;
    image {
      width: 24rpx;
      height: 24rpx;
      margin-right: 16rpx;
    }
  }

  .auth-btn {
    width: 100%;
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-column-gap: 24rpx;
    margin: 30rpx 0 20rpx;
    .btn {
      font-family: PingFangSC-Medium;
      font-size: 32rpx;
      color: #99302f;
      background-color: #ffffff;
      border-radius: 20rpx;
      border: 2rpx solid #99302f;
      height: 88rpx;
      line-height: 88rpx;
      text-align: center;
    }
    .com-btn {
      background-color: #ebd6d7;
      border-color: #ebd6d7;
    }
  }
  .phone-btn {
    border: 0;
    text-align: right;
    padding: 0;
    line-height: 1;
    font-family: PingFangSC-Regular;
    font-size: 28rpx;
    color: #99302f;
  }
  .fie-lable {
    font-family: PingFangSC-Regular;
    font-size: 28rpx;
    color: #302e2d;
  }
  .input-holder {
    font-family: PingFangSC-Regular;
    font-size: 28rpx;
    color: #88868b;
  }
}

authMes.json

javascript 复制代码
{
  "component": true,
  "usingComponents": {
    "van-field": "@vant/weapp/field/index",
    "van-popup": "@vant/weapp/popup/index"
  }
}

app.apis是封装的微信小程序请求接口的方法详细见这篇文章

相关推荐
三天不学习3 小时前
使用Cursor + Devbox + Uniapp 一站式AI编程开发移动端(App、H5、小程序)
小程序·uni-app·ai编程
刘大浪16 小时前
uniapp 小程序 学习(一)
学习·小程序·uni-app
炫彩@之星1 天前
微信小程序渗透测试指北(附案例)
微信小程序·小程序
—Qeyser1 天前
让 Deepseek 写电器电费计算器小程序
ai·chatgpt·小程序·deepseek
27669582921 天前
朴朴超市小程序 sign-v2 分析
java·python·小程序·逆向分析·朴朴超市·sign-v2·朴朴
说私域2 天前
新零售视域下实体与虚拟店融合的技术逻辑与商业模式创新——基于开源AI智能名片与链动2+1模式的S2B2C生态构建
人工智能·小程序·开源·零售
java1234_小锋2 天前
[免费]微信小程序音乐播放器(爬取网易云音乐数据)(node.js后端)【论文+源码】
微信小程序·小程序·node.js·音乐播放器·网易云音乐
野盒子2 天前
前端面试题 微信小程序兼容性问题与组件适配策略
前端·javascript·面试·微信小程序·小程序·cocoa
胡斌附体2 天前
uniapp小程序不支持动态组件问题
小程序·uni-app·if-else·动态组件·不支持·编译异常
小妖6662 天前
uni-app 小程序 Cannot read property ‘addEventListener‘ of undefined, mounted hook
小程序·uni-app