这几天遇到一个问题,就是使用微信小程序自带的组件wx.showActionSheet(object),并且在这里添加分享按钮,但查看了小程序API文档后发现,分享功能调用的onShareAppMessage(options) 函数,设置该页面的转发信息。
微信小程序API文档:https://developers.weixin.qq.com/miniprogram/dev/api/
先介绍下Page.onShareAppMessage:
示例代码:
Page({
onShareAppMessage: function (res) {
if (res.from === 'button') {
// 来自页面内转发按钮
console.log(res.target)
}
return {
title: '自定义转发标题',
path: '/page/user?id=123'
}
}
})
只要调用onShareAppMessage,在小程序页面中就可以在右上角点击转发功能。然后需要在页面中定义按钮点击,弹出转发界面,而不是通过右上角的转发,所以需要我们在页面中添加button按钮。
<button open-type="share">分享</button>
接下来说下wx.showActionSheet:
示例代码:
wx.showActionSheet({
itemList: ['A', 'B', 'C'],
success: function(res) {
console.log(res.tapIndex)
},
fail: function(res) {
console.log(res.errMsg)
}
})
这样可以实现弹出操作列表,如下图:
那么问题来了,在wx.showActionSheet中无法直接添加分享按钮,在百度上查了后也说利用这个无法直接实现分享功能,只用通过自定义的action-sheet组件才能够实现,于是我就重新开始写。
wxml
<button @tap="listenerButton">
<icon class="icon fa fa-external-link"></icon>分享
</button>
<!--默认action-sheet为隐藏,由button触发-->
<action-sheet hidden="{{actionSheetHidden}}" bindchange="listenerActionSheet">
<action-sheet-item>
<button open-type="share">分享给好友</button>
</action-sheet-item>
<action-sheet-item>生成分享卡片</action-sheet-item>
<!--自动隐藏action-sheet-->
<action-sheet-cancel>取消</action-sheet-cancel>
</action-sheet>
JS
Page({
data:{
// text:"这是一个页面"
actionSheetHidden: true,
},
listenerButton: function() {
this.setData({
actionSheetHidden: !this.data.actionSheetHidden
});
},
listenerActionSheet:function() {
this.setData({
actionSheetHidden: !this.data.actionSheetHidden
})
},
onLoad:function(options){
// 页面初始化 options为页面跳转所带来的参数
},
onReady:function(){
// 页面渲染完成
},
onShow:function(){
// 页面显示
},
onHide:function(){
// 页面隐藏
},
onUnload:function(){
// 页面关闭
}
})
在action-sheet-item中放入分享按钮,这样就可以实现操作列表中分享小程序功能。