小程序自定义分享和传值功能&检查是否分享成功并指定群和个人的分享

一,官网的例子

<button open-type='share'>分享好友</button>

 

/**
* 用户点击右上角分享
*/
onShareAppMessage: function(ops) {
    // 进行你的操作
}



二,自定义分享

wxml:
<button id="mairu" data-item="{{item}}" open-type='share'>分享好友</button>

 

// id可以是button按钮上带过来的值,相对应,item也一样,可以是接口请求过来的对象
onShareAppMessage: function(res) {
 
    // 如果是右上角的分享,直接返回return
    return { 
        title: '标题',
        imageUrl:  `图片地址注意符号` ,
        path: `pages/index/index`, //分享当前页面
    }

 

    // 点击按钮分享指定页面
    if (res.from === 'button') {
        // 如果按钮是1
        if(res.target.id == 'mairu'){
            return {
                title: '买入',
                imageUrl:  `图片地址注意符号` ,
                path: `pages/index/index`, //点击分享的图片进到哪一个页面,相当于分享指定的页面
                success: function (res) {
                    // 转发成功
                },
                fail: function (res) {
                    // 转发失败
                }
            }
        }
        // 如果按钮是卖出
        else{
            return {
                title: '卖出',
                imageUrl:  `图片地址注意符号` ,
                path: `pages/index/index?id=`+this.data.id, //点击分享的图片进到哪一个页面,相当于分享指定的页面
                success: function (res) {
                    // 转发成功
                },
                fail: function (res) {
                    // 转发失败
                }
            }
        }
    }
  }

 

// 如果点击的卖出按钮在页面中获取id的值
onLoad: function (options) {
    //打印获取的数据
    console.log(options.id)
},



三,检查是否分享成功并指定群和个人的分享

onShareAppMessage: function () {
    //转发时携带 shareTicket才能在回调中获取到shareTickets
    wx.showShareMenu({
      withShareTicket: true
    }) 
    return {
      title: '转发时显示的标题',
      path: '转发的页面路径',
      success:function(res) {
        console.log('--- 转发回调 ---', res);
        //onShareAppMessage回调的shareTickets,如果没有,就说明不是转发到群聊的
        console.log('--- shareTickets ---', res.shareTickets);
        //转发到群里的才会有shareTickets
        if(res.shareTickets && res.shareTickets[0]) {
            //获取转发的详细信息
            wx.getShareInfo({
            shareTicket: res.shareTickets[0],
            success:function(res) {
              },
            fail:function(error){
            }
          })
        }
      },
      fail:function (error){
      }
    }
  }
 
以上就是我对小程序分享的总结,参考自https://blog.csdn.net/y_z_w123/article/details/81985064?utm_source=blogxgwz6
posted on 2020-03-28 17:26  吃的快不吐骨头  阅读(1289)  评论(0)    收藏  举报