微信小程序自定义分享功能开发笔记

  1. 要在分享的页面中定义onShareAppMessage 方法,只有定义了此事件处理函数,右上角菜单才会显示“转发”按钮
  2. onShareAppMessage触发方式有两种,一种是通过下面示例的button方式触发,一种是右上角菜单转发

  3. onShareAppMessage是同步方法,如果我们要自定义复杂的转发逻辑,需要通过其promise方法实现,使用方法如下面示例

  4. 如使用promise方法定义转发内容,也需定义其他基础配置项,如promise该参数存在,则以 其resolve 结果为准,如果三秒内不 resolve,分享会使用默认参数

<button class="resetBtn mangeL-box" open-type="share" data-info='{
   
   {videoInfo}}'>
    <view class="icon-name">分享</view>
</button>
   onShareAppMessage({from,target}) {
        // 判断from类型来确定是按钮分享还是三个点分享
        if (from == 'button') {
            let video = target.dataset.info
            const promise = new Promise(resolve => {
                this.creatShare(video).then(res => {
                    resolve(res)
                })
            })
            
            return {
                title: '请欣赏我的课文朗读作品,点赞+评论。',
                path: `/pages/index/index`,
                imageUrl: xxx,
                promise
            }
        } else {
            return {
                title: '课文朗读,从未如此有趣。',
                path: `xxx`,
                imageUrl: 'http://xxx/v3/shareContent.png'
            }
        }
    }
  creatShare(video) {
        return new Promise((resolve, reject) => {
            // 我在这里是使用canvas绘图分享的,绘制代码已删除,主要是通过reslove()抛出分享的配置项
            wx.canvasToTempFilePath({
                canvas: canvas,
                success(res) {
                    resolve({
                        title: '请欣赏我的课文朗读作品,点赞+评论。',
                        path: `/pages/index/index?readId=${video.userRead.id}`,
                        imageUrl: res.tempFilePath
                    })
                },
                fail(res) {
                    reject()
                }
            }, this)
        })
    },

猜你喜欢

转载自blog.csdn.net/qq_42044542/article/details/128340110