官方的分享
点击右上角的三个点
/*** 用户点击右上角分享*/onShareAppMessage: function(ops) {wx.showShareMenu({withShareTicket: true})}
自定义分享
wxml
<button open-type='share'>分享好友</button>
/*** 生命周期函数--监听页面加载*/onLoad() {wx.showShareMenu({// 要求小程序返回分享目标信息withShareTicket: true});},onShareAppMessage: function(ops) {if (ops.from === 'button') {// 来自页面内转发按钮console.log(ops.target)}return {title: '标题',imageUrl: `图片地址注意符号` ,desc: '描述',path: `pages/index/index`, //点击分享的图片进到哪一个页面success: function (res) {// 转发成功console.log("转发成功:" + JSON.stringify(res));},fail: function (res) {// 转发失败console.log("转发失败:" + JSON.stringify(res));}}}
结果
区分不同按钮的分享
wxml
<button id='btn' open-type="share" plain='true'></button>
onShareAppMessage: function (res) {if (res.from === 'button') {// 来自页面内转发按钮console.log(res.target.id)console.log(res.from)//区分按钮分享if (res.target.id === "btn") {return {title: '求助,下面图中是什么菜啊?',path: '/pages/title/title',success: function (res) {// 转发成功},fail: function (res) {// 转发失败}}}}//右上角分享return {title: '标题',path: `pages/index/index`,imageUrl: ``,success: function (res) {// 转发成功console.log("转发成功:" + JSON.stringify(res));},fail: function (res) {// 转发失败console.log("转发失败:" + JSON.stringify(res));}}}
带参数分享&转发和获取
onShareAppMessage: function (res) {//右上角分享 this.data.id取得data里面的数据return {title: '标题',path: `pages/index/index?id=`+ this.data.id,imageUrl: ``,success: function (res) {// 转发成功console.log("转发成功:" + JSON.stringify(res));},fail: function (res) {// 转发失败console.log("转发失败:" + JSON.stringify(res));}}}
注意调试的时候在手机打开调试 页面(自己分享自己点击)
因为是直接跳转到index页面所以在index.js页面获取
onLoad: function (options) {//打印获取的数据console.log(options.id)},
检查是否分享成功并指定群和个人的分享
onShareAppMessage: function () {//转发时携带 shareTicket才能在回调中获取到shareTicketswx.showShareMenu({withShareTicket: true})return {title: '转发时显示的标题',path: '转发的页面路径',success:function(res) {console.log('--- 转发回调 ---', res);//onShareAppMessage回调的shareTickets,如果没有,就说明不是转发到群聊的console.log('--- shareTickets ---', res.shareTickets);//转发到群里的才会有shareTicketsif(res.shareTickets && res.shareTickets[0]) {//获取转发的详细信息wx.getShareInfo({shareTicket: res.shareTickets[0],success:function(res) {},fail:function(error){}})}},fail:function (error){}}}
