微信小程序之分享或转发功能(自定义button样式)

时间:2022-11-18 20:53:44

小程序页面内发起转发

通过给 button 组件设置属性 open-type="share",可以在用户点击按钮后触发 Page.onShareAppMessage 事件,如果当前页面没有定义此事件,则点击后无效果。相关组件:button

wxml:

<!-- 分享 -->
<!--/pages/detail/detail.wxml-->
<view class='share'>
<image src='/images/share.png'></image>
<text>分享</text>
<button open-type='share'></button>
</view>

wxss:

.share {
height: 120rpx;
width: 120rpx;
position: fixed;
bottom: 170rpx;
right: 30rpx;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: 24rpx;
background: rgba(0, 0, 0, .6);
border-radius: 50%;
z-index: 10;
}
.share image {
height: 70rpx;
width: 70rpx;
}
.share text {
color: #fff;
} .share button {
position: absolute;
height: 100%;
width: 100%;
opacity: 0.1;
z-index: 99;
}

js:

onShareAppMessage(res) {
let id = wx.getStorageSync('shareId') // 分享产品的Id
if (res.from === 'button') {
// 来自页面内转发按钮
console.log(res.target)
}
return {
title: '转发标题',
path: `pages/detail/detail?id=${id}` // 分享后打开的页面
}
},

按钮样式如图:

微信小程序之分享或转发功能(自定义button样式)