uniapp之小程序自定义分享

仅在 微信小程序 & 字节(抖音)小程序 中验证过

分享调用流程

借用字节小程序文档中的图,原文地址,微信小程序的原理也是一致的

image.png

从上图中可以看出,调用 onShareAppMessage 的 时机就是用户点击了菜单中的分享 或者 自定义的分享按钮 时候

自定义分享参数

  1. 注册 onShareAppMessage
    此事件需要在 页面中 注册,组件中注册是无效的。但是执行分享的操作是可以在组件中的,最终会触发这些组件所在的页面的 onShareAppMessage 方法。
import { onShareAppMessage } from "@dcloudio/uni-app";
onShareAppMessage((options) => {
  console.log('获得的参数:', options);
  // let { path, title, imageUrl } = options.target.dataset.share;
  return {
    title: "个人主页",
    desc: "测试的内容",
    path: "/pages/user/index",
    imageUrl: "https://we-retail-static-1300977798.cos.ap-guangzhou.myqcloud.com/retail-ui/components-exp/avatar/avatar-1.jpg"
  };
})
  1. Button 中定义分享参数
 <button class="btn-init" 
         open-type="share"
         :data-share="{
            title: '啦啦啦',
            path: '11111',
            imageUrl: 'https://we-retail-static-1300977798.cos.ap-guangzhou.myqcloud.com/retail-ui/components-exp/avatar/avatar-1.jpg'
          }"
        >
        <view class="cell-item">
            <view class="cell-title">
              <view>页面分享</view>
            </view>
            <image style="width: 20px; height: 20px; display: block;" src="@/static/icon/arrow_right.svg" />
       </view>
</button>

data-share 中的就是自定义的参数,将会在 onShareAppMessage 的 options 中获取

image.png

可以依据上面的参数进行各种行为的数据处理

总结

只要保证数据能在触发分享函数之前获取成功,即可让自定义分享成功。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容