微信小程序之轉(zhuǎn)發(fā)功能(附效果圖和源碼)

小程序分享或轉(zhuǎn)發(fā)有兩種方式,一種是通過(guò)在頁(yè)面中自定義按鈕的形式,另外一種只需要在js中定義 onShareAppMessage 函數(shù),頁(yè)面右上角就會(huì)出現(xiàn)轉(zhuǎn)發(fā)的按鈕。詳細(xì)文檔請(qǐng)參閱微信官方文檔微信轉(zhuǎn)發(fā)API。目前小程序好像暫不支持轉(zhuǎn)發(fā)到微信朋友圈。

效果圖:


sharePage.png

sharePage2.png
shareFriends.png

step1:在需要轉(zhuǎn)發(fā)功能的wxml中定義一個(gè)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>梅賽德斯-奔馳旨在為消費(fèi)者服務(wù)</text>
      <button  class='bg-c' type="primary" hover-class="other-button-hover">預(yù)約</button>
    </view>
  </view> 
</view>

step2:在js中加上onShareAppMessage函數(shù)

示例代碼:

 /**
* 用戶點(diǎn)擊右上角分享(index.js)
*/
 onShareAppMessage: function (ops) {
   if (ops.from === 'button') {
     // 來(lái)自頁(yè)面內(nèi)轉(zhuǎn)發(fā)按鈕
     console.log(ops.target)
   }
   return {
     title: 'xx小程序',
     path: 'pages/index/index?id=123&age=18',  // 路徑,傳遞參數(shù)到指定頁(yè)面。
     imageUrl:'../../imgs/xx.png' // 分享的封面圖
     success: function (res) {
       // 轉(zhuǎn)發(fā)成功
       console.log("轉(zhuǎn)發(fā)成功:" + JSON.stringify(res));
     },
     fail: function (res) {
       // 轉(zhuǎn)發(fā)失敗
       console.log("轉(zhuǎn)發(fā)失敗:" + JSON.stringify(res));
     }
   }

 }

獲取參數(shù)

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

官方說(shuō)明:


github地址:微信轉(zhuǎn)發(fā)功能 歡迎start

其它文章請(qǐng)?jiān)L問(wèn):

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容