微信小程序:简单实现“转发功能”

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>XX标题</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>XX提示或文字</text>
      <button  class='bg-c' type="primary" hover-class="other-button hover">call</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',
     success: function (res) {
       // 转发成功
       console.log("转发成功:" + JSON.stringify(res));
     },
     fail: function (res) {
       // 转发失败
       console.log("转发失败:" + JSON.stringify(res));
     }
   }

 }
微信小程序:简单实现“转发功能”
官方文档(附图说明)