最新小程序获取头像及关注公众号引导和分享功能

Z技术 2021年11月13日 794次浏览

1,视图代码

   <view class="userinfo">
      <block wx:if="{{!hasUserInfo}}">
        <button wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile">我的头像</button>
        <button wx:else open-type="getUserInfo" bindgetuserinfo="getUserInfo">我的头像</button>
      </block>
      <block wx:else>
        <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
        <text class="userinfo-nickname">{{userInfo.nickName}}</text>
      </block>
    </view>

2,js代码

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUseGetUserProfile:false,
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },
  getUserProfile(e) {
    wx.login({
      success (res) {
        //获取code
        console.log(res)
      }
    }),
    wx.getUserProfile({
      desc: '用于展示会员资料', 
      success: (res) => {
       //获取用户信息
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  getUserInfo(e) {
    // 不推荐自2021年4月13日起,getUserInfo返回匿名的用户个人信息
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})

3,公众号引导代码

<!--公众号引导-->
<view style="margin-top:50%;">
 <official-account></official-account>
</view>

4,增加分享给好友功能,在页面js文件中增加下面的函数

Page(
 onShareAppMessage(res){
    if(res.from=='button'){
      console.log(res.target,res)
    }
    return {
      title:'点击参加TechZ活动', //分享的标题
      path:'/pages/index/index.wxml',//分享后进入的页面
      imageUrl:'/pages/images/shareimg.png'//分享缩略图
    }
  }
)

5,增加分享到朋友圈,和第4点一样

Page(
  onShareTimeline: function() {
    return {
      title: '点击参加TechZ活动',
      path: '/pages/index/index.wxml',
      imageUrl:'/pages/images/shareimg.png',
      query: 'test=1234'
    }
  }
)