小程序右上角分享按钮和自定义按钮

539 阅读1分钟

1.wx.showShareMenu(Object object)

调用显示出默认分享按钮,一般可以在onLoad周期内调用就可以

wx.showShareMenu({
  withShareTicket: true, // 展示默认分享按钮
  menus: ['shareAppMessage', 'shareTimeline'] //分享好友 | 分享朋友圈
})

2.onShareAppMessage(Object object)

监听用户点击页面内转发按钮(button 组件 open-type="share")或右上角菜单“转发”按钮的行为,并自定义转发内容。 右上角菜单“转发”按钮的行为

Page({ //右上角菜单“转发”按钮的行为
  onShareAppMessage() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '自定义转发标题'
        })
      }, 2000)
    })
    return {
      title: '自定义转发标题',
      path: '/page/user?id=123',
      promise 
    }
  }
})

自定义按钮点击行为

//wxml
<button style="padding: 0;margin: 0;width:100%;" class='button' open-type="share">
  <text>分享小程序</text>
</button>
//javascript
onShareAppMessage () { //分享小程序页面
    return {
      title:'自定义标题',
      path: 'page/xxx/xx/xxx/?id=xxx&name=xxxx', //传入id参数可以渲染商品详情类的页面
      imageUrl:"../../images/headimg/back.jpeg", // 自定义分享时好友看到的图片
      success (res) { //成功时回调
        console.log('成功', res)
      }
    }
  },

3.onShareTimeline()

监听右上角菜单“分享到朋友圈”按钮的行为,并自定义分享内容。 只有定义了此事件处理函数,右上角菜单才会显示“分享到朋友圈”按钮。 **不同点:**事件处理函数返回一个 Object,用于自定义分享内容,不支持自定义页面路径。

onShareTimeline() {
    return {
      title: this.data.questionsList[this.data.questionIndex].title, //自定义标题
      query: { //用户访问时onLoad(options)生命周期函数的options
        text: this.data.text,
        value: this.data.isDesc,
        index: this.data.questionIndex,
      },
      imageUrl: "自定义分享图片" // 不定义默认使用本页面
    }
  },