微信小程序页面实现分享功能_微信小程序分享页面
监听用户点击页面内转发按钮(button 组件
open-type=\"share\"
),并自定义转发内容。使用
onShareAppMessage
实现页面的分享功能,完整的文档可前往小程序文档中心查看onShareAppMessage
一.使用自定义的分享方式(用户点击页面内的按钮进行分享):
在需要分享的页面中添加一个按钮button:
属性为 open-type=\"share\"
在微信小程序的页面的js文件中添加一个函数:onShareAppMessage(Object object)
函数格式见下面内容
二.使用默认的分享方式
在微信小程序的页面的js文件中添加一个函数:onShareAppMessage(Object object)
相较于上面的少了添加button按钮
代码展示:
Page({ data: { activity_infor: { id: 520, name: \"广州大学实验室开放日\", image: \"/assets/share-banner.jpg\" } }, onShareAppMessage(res) { console.log(\'分享来源:\', res.from); // button 或 menu if (res.from === \'button\') { console.log(\'分享按钮元素:\', res.target); } const { id, name, image } = this.data.activity_infor; // 使用 promise 异步设置分享内容(模拟异步请求) const promise = new Promise(resolve => { setTimeout(() => { resolve({ title: `【热门活动】${name}`, path: `/pages/activity-detail/activity-detail?id=${id}`, imageUrl: image }); }, 1000); }); return { title: `【热门活动】${name}`, path: `/pages/activity-detail/activity-detail?id=${id}`, imageUrl: image, promise }; } });
title
path
/
开头)imageUrl
promise
三.分享到朋友圈
采用微信小程序的onShareTimeline()函数:
Page({ data: { activity_infor: { id: 123, name: \"广州大学实验室开放日\" } }, // 分享到朋友圈 onShareTimeline() { const { id, name } = this.data.activity_infor return { title: `快来参加:${name}`, // 分享标题 query: `id=${id}`, // 携带参数,不能包含页面路径 imageUrl: \'/assets/share-cover.jpg\' // 自定义图片路径,可以是本地文件或者网络图片 } }})