小程序分享或轉發有兩種方式,一種是通過在頁面中自定義按鈕的形式,另外一種只需要在js中定義 onShareAppMessage 函數,頁面右上角就會出現轉發的按鈕。詳細文檔請參閱微信官方文檔微信轉發API。目前小程序好像暫不支持轉發到微信朋友圈。
效果圖:
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',
success: function (res) {
// 轉發成功
console.log("轉發成功:" + JSON.stringify(res));
},
fail: function (res) {
// 轉發失敗
console.log("轉發失敗:" + JSON.stringify(res));
}
}
}
官方說明: