> 技术文档 > 微信小程序的分享功能_微信小程序分享

微信小程序的分享功能_微信小程序分享


一、小程序的分享方式有两种

  1. 点击页面中的按钮进行分享
  2. 通过右上角的三个点进行分享

二、功能实现

(1)按钮分享

代码:

        关键点:

        1.使用button

        2.open-type的类型是share

(2)通过右上角分享

代码:

 // 分享至好友/群聊onShareAppMessage(res) {const userInfo = JSON.parse(uni.getStorageSync(\'userInfo\') || \'{}\')return {title: \'欢迎使用小程序\',path: \'pages/index/index?shareId=\' + userInfo.userId,imageUrl: \'/static/images/share.png\'}}, // 分享至朋友圈onShareTimeline() {},

        注意:

        1.onShareAppMessage和onShow同级

        2.res的参数:

                a) from    

                        分享事件来源:button(页面内分享按钮)、menu(右上角分享按钮)

                b)target    

                        如果 from 值是 button,则 target 是触发这次分享事件的 button,否则为                         undefined(可根据target的id来判断是哪个按钮进行的分享)

                c)webViewUrl  

                        页面中包含  组件时,返回当前  的url

        3.path后面添加参数,可在点击分享链接时,通过onShow获取,后续进行操作

onShow(options) {console.log(\'options\', options)console.log(\'options.query\', options.query)}

 三、注意点

1、如果使用button按钮进行分享,且不需要对标题图片等信息进行修改,可以只使用一个button,如果调整则需要加上onShareAppMessage处理函数

2、onShareAppMessage的添加位置

        a)必须加在页面中,加在组件中不生效

        b)加在单个页面只有那个页面可以通过右上角进行分享,其他页面不可以

        c)加在全局

四、onShareAppMessage全局分享

1、在components文件夹下创建share.js

export default {// 分享至好友/群聊onShareAppMessage(res) {const userInfo = JSON.parse(uni.getStorageSync(\'userInfo\') || \'{}\')return {title: \'欢迎使用小程序\',path: \'pages/index/index?shareId=\' + userInfo.userId,imageUrl: \'/static/images/share.png\'}},// 分享至朋友圈onShareTimeline() {},}

2、在main.js中插入代码

import share from \'./components/share.js\'Vue.mixin(share)

这样就可以在任意页面都使用右上角的分享