一、简单分享
对于微信小程序分享非常简单,我们只需要调用onShareAppMessage然后设置参数就ok。
onShareAppMessage() {
return {
title: `分享标题`, //分享的标题
path: `/pages/subPages/shopDetail/main?id=${this.goodsId}&shareId=${
this.$store.state.userinfo.id
}`, //分享的链接
imageUrl: this.detail.image //分享的封面图
};
}
这样点击右上角的分享就可以成功,如果没有设置封面图,就会以当前的页面截图作为封面图。我们也可以设置成点击按钮来进行分享。
<button v-show="showOthers" open-type="share" class="share-item">
<div class="share-item-text">分享给朋友</div>
</button>
分享成功后,在跳转的页面“/pages/subPages/shopDetail/main”’中接收传参。
onLoad: function(options) {
this.scene = decodeURIComponent(options.scene);
let sceneArray = this.scene.split(",");
this.goodsId = sceneArray[0];
this.shareId = sceneArray[1];
}
二、改变分享内容
在上面的分享中,我们只能在一个页面分享特点的内容,如果在一个列表页中,点击不同的列表项,分享不同的列表项的内容,就需要动态来改变分享的内容。
<button open-type='share' class="pt-share" :data-name="item">
分享
</button>
重点在于data-name,将一个对象赋值给data-name,其中item结构为
item={
title:'标题',
productId:'10',
groupBuyId:'2',
image:'..........',
}
然后我们就可以在onShareAppMessage获取和改变分享内容
onShareAppMessage(options) {
var shareVal= {
title: `分享标题`,
path: `/pages/shopDetail/main`, //默认分享链接
imageUrl: this.shareitem.image, //默认分享封面
success: function(res){
// 转发成功之后的回调
if(res.errMsg == 'shareAppMessage:ok'){
//在这里做一些成功后的操作
}
},
}
//在这里获取传参和改变分享内容
if( options.from == 'button' ){
//获取data-name中的对象
var eData = options.target.dataset.name;
console.log( options);
shareVal.title =`${eData.title}`,
shareVal.path=`/pages/shopDetail/main?shareId=${this.$store.state.userinfo.id}id=${eData.productId}&groupBuyId=${eData.groupBuyId}`,
shareVal.imageUrl=eData.image
}
return shareVal;
}
这样就可以实现动态改变分享内容进行分享。