微信小程序之转发功能(附效果图和源码)

小程序分享或转发有两种方式,一种是通过在页面中自定义按钮的形式,另外一种只需要在js中定义 onShareAppMessage 函数,页面右上角就会出现转发的按钮。详细文档请参阅微信官方文档微信转发API。目前小程序好像暂不支持转发到微信朋友圈。

效果图:


sharePage.png

sharePage2.png
shareFriends.png

step1:在需要转发功能的wxml中定义一个button按钮,按钮的属性中加上open-type="share"。

示例代码:

<!--index.wxml-->
<view class='container'>
  <view class='card b-shadow'>
    <view class='card-content'>
      <image mode="widthFix"  src='../../images/benchi.png'></image> 
    </view>
    <view class='carDesc carDesc1'>
      <text>奔驰A230</text>
      <button class='share' id="shareBtn" open-type="share" type="primary" hover-class="other-button-hover">
        <image src='../../images/share.png'></image>
        分享
      </button>
    </view>
    <view class='carDesc carDesc2'>
      <text>梅赛德斯-奔驰旨在为消费者服务</text>
      <button  class='bg-c' type="primary" hover-class="other-button-hover">预约</button>
    </view>
  </view> 
</view>

step2:在js中加上onShareAppMessage函数

示例代码:

 /**
* 用户点击右上角分享(index.js)
*/
 onShareAppMessage: function (ops) {
   if (ops.from === 'button') {
     // 来自页面内转发按钮
     console.log(ops.target)
   }
   return {
     title: 'xx小程序',
     path: 'pages/index/index?id=123&age=18',  // 路径,传递参数到指定页面。
     imageUrl:'../../imgs/xx.png' // 分享的封面图
     success: function (res) {
       // 转发成功
       console.log("转发成功:" + JSON.stringify(res));
     },
     fail: function (res) {
       // 转发失败
       console.log("转发失败:" + JSON.stringify(res));
     }
   }

 }

获取参数

// index.js
Page({
    onLoad: function(options) {
        console.log(options);
        console.log(options.id);
        console.log(options.age);
    }
})

官方说明:


github地址:微信转发功能 欢迎start

其它文章请访问:

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

推荐阅读更多精彩内容