在vue中使用weixin-js-sdk自定义微信分享效果

 

 

 

 

在做微信分享的时候,产品要求分享效果要有文字和图片,使用weixin-js-sdk解决了,

原始的分享效果:

 

使用微信JS-SDK的分享效果:

首先需要引入weixin-js-sdk

npm install weixin-js-sdk --save

在main.js中引用

 

 

* 微信分享后自定义缩略图及标题
 
import {getSignature} from '../services/wechat.js';
export default {
data: function() {
return {
wxReady: false,
apiReady: false,
wxShare: {}
};
},
created() {
const _this = this;
getSignature({url: location.href})
.then(data => {
const wx = this.$wx;
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: data.appid, // 必填,公众号的唯一标识
timestamp: data.timestamp, // 必填,生成签名的时间戳
nonceStr: data.nonceStr, // 必填,生成签名的随机串
signature: data.signature, // 必填,签名,见附录1
jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline', 'onMenuShareQQ'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
wx.ready(function() {
_this.wxReady = true;
_this.toShare();
});
wx.error(function() {
// config信息验证失败会执行error函数
});
})
.catch(error => {
/* eslint-disable */
console.error('获取微信签名出错', error);
});
},
methods: {
setWxShare: function(params) {
this.apiReady = true;
const config = {
link: window.location.href,
...params
};
this.wxShare = config;
this.toShare();
},
toShare: function() {
if (this.apiReady && this.wxReady) {
const wx = this.$wx;
const config = this.wxShare;
wx.onMenuShareAppMessage(config); //分享给朋友
wx.onMenuShareTimeline(config); //分享到朋友圈
wx.onMenuShareQQ(config); //分享给手机QQ
}
}
}
};

然后再文件中引入既可:

 

posted @ 2018-11-01 15:32  采姑娘的小乌龟  阅读(1099)  评论(0编辑  收藏  举报