1. 程式人生 > >微信小程式獲得微信頭像和暱稱

微信小程式獲得微信頭像和暱稱


{
  wx.getSetting({
    success: res => {
      if (res.authSetting && res.authSetting['scope.userInfo']) {
        // 已經授權,可以直接呼叫 getUserInfo 獲取頭像暱稱
        wx.getUserInfo({
          success: function (data) {
            console.log(data.userInfo);
            // {
            //   avatarUrl: '微信頭像img檔案path'
            //   nickname: '微信暱稱'
            // }
          }
        });
      } else {
        this.showShouquan = true; // 開啟模態框進行授權
      }
    }
  });
}


<template>
    <div>
        <!-- 這裡採用vantui進行彈框,只不過把彈出框的button型別設定成了"getUserInfo",原理就是下面這個button
        <button wx:if="{{showShouquan}}" open-type="getUserInfo" bindgetuserinfo="getUserInfoFromWx">授權登入</button> -->
        <van-dialog use-slot async-close :show="showShouquan" show-cancel-button confirm-button-open-type="getUserInfo"
            @close="cancelShouquan" @getuserinfo="getUserInfoFromWx">
            <h4 class="wx-shouquan-title">微信授權</h4>
            <p class="wx-shouquan-content">
                xxxxxxx小程式將獲得您的微信頭像、暱稱等公開訊息
            </p>
        </van-dialog>
        <div>
</template>

    getUserInfoFromWx (e) {
      this.$store.state.user_userinfo = e.mp.detail.userInfo;
      this.showShouquan = false;
    },
    cancelShouquan () {
      this.showShouquan = false;
    },

來源:https://segmentfault.com/a/1190000017496137