uni-app开发微信小程序如何实现分享功能_uniapp 微信小程序分享
在uni-app中实现微信小程序分享功能可通过以下方式实现:
一、基础页面级配置
-
分享好友配置
在页面的.vue
文件中配置onShareAppMessage
生命周期函数:
export default { onShareAppMessage(res) { return { title: \'自定义标题\', path: \'/pages/index/index?id=123\', imageUrl: \'/static/share.png\' }; }}
2.分享朋友圈配置
需同时配置onShareTimeline
生命周期函数:
export default { onShareTimeline() { return { title: \'朋友圈分享标题\', query: \'id=123\', imageUrl: \'/static/share.png\' }; }}
需调用uni.showShareMenu({ menus: [\'shareAppMessage\', \'shareTimeline\'] })
启用两种分享方式
3.自定义触发按钮
通过设置覆盖默认分享按钮样式
微信小程序会自动调微信 onShareAppMessage
。
- 仅支持分享到微信好友,不支持朋友圈。
- 分享内容受限于微信小程序规范(如路径需在白名单内)。
二、注意事项
- 分享权限
需在manifest.json
中配置微信小程序的AppID
并确保已开通分享权限。 - 图片路径
图片建议使用本地路径,网络图片需添加到微信域名白名单。 - 调试工具
使用微信开发者工具模拟分享时,部分功能需真机调试验证。
三、使用Mixin提取重复代码
1.创建共享mixin文件
新建utils/shareMixin.js
文件,定义全局分享逻辑:
通过data
字段实现配置参数的可覆盖性
export default { data() { return { // 可全局覆盖的默认参数 shareConfig: { title: \'默认分享标题\', path: \'/pages/index/index\', imageUrl: \'/static/share-default.png\' } } }, onShareAppMessage() { return { title: this.shareConfig.title, path: `${this.shareConfig.path}?ref=${Date.now()}`, imageUrl: this.shareConfig.imageUrl } }, onShareTimeline() { return { title: this.shareConfig.title, query: `ref=${Date.now()}`, imageUrl: this.shareConfig.imageUrl } }}
2.全局注册mixin
在main.js
中引入并混入:
import shareMixin from \'@/utils/shareMixin\'Vue.mixin(shareMixin)
3.页面级定制覆盖
在需要特殊处理的页面中,直接覆盖默认配置:
export default { onLoad() { // 动态修改当前页面的分享参数 this.shareConfig = { title: \'商品详情页\', path: \'/pages/detail?id=123\', imageUrl: \'/static/product-share.jpg\' } // 激活分享菜单(需在页面生命周期调用) uni.showShareMenu({ menus: [\'shareAppMessage\', \'shareTimeline\'] }) }}
4.统一启用分享功能
在App.vue
的onLaunch
中全局激活分享菜单:
避免在每个页面单独调用激活接口
export default { onLaunch() { // 全局启用分享功能 uni.showShareMenu({ withShareTicket: true, menus: [\'shareAppMessage\', \'shareTimeline\'] }) }}