## 对onShareAppMessage进行封装,分为分享到个人和分享到群
1.底层代码封装到util工具js里面
~~~
function onShareAppMessage(title, path, callback, imageUrl) {
//设置一个默认分享背景图片
let defaultImageUrl = '../../images/share.jpg';
return {
title: title,
path: path,
imageUrl: imageUrl || defaultImageUrl,
success(res) {
console.log("转发成功!");
if (!res.shareTickets) {
//分享到个人
api.shareFriend().then(() => {
console.warn("shareFriendSuccess!");
//执行转发成功以后的回调函数
callback && callback();
});
} else {
//分享到群
let st = res.shareTickets[0];
wx.getShareInfo({
shareTicket: st,
success(res) {
let iv = res.iv
let encryptedData = res.encryptedData;
api.groupShare(encryptedData, iv).then(() => {
console.warn("groupShareSuccess!");
//执行转发成功以后的回调函数
callback && callback();
});
}
});
}
},
fail: function (res) {
console.log("转发失败!");
}
};
}
//将其方法导出
module.exports = {
onShareAppMessage: onShareAppMessage
}
~~~
### 2.调用示例
~~~
/**
* 用户点击右上角分享
*/
onShareAppMessage: function (e) {
let nickName = '';
try {
nickName = getApp().globalData.userInfo.nickName;
} catch (e) {
console.warn("用户未授权!");
nickName = '有人';
}
let title = `[${nickName}@我]帮我看看这个叫什么,经常吃却不知道名字`;;
let path = '/pages/index/index';
let shareCallBack = () => {
//分享成功后做的事情
//
//
};
//此处调用封装好的分享代码
return util.onShareAppMessage(title, path, shareCallBack);
},
~~~