vue專案之微信分享
1. npm install weixin-js-sdk --save
2. mian.js
引入 import wx from 'weixin-js-sdk'
Vue.prototype.wx = wx
3.wxapi.js 封裝的公共js
import wx from 'weixin-js-sdk'
import Vue from 'vue'
export function wxShare(r, wxParams) {
let links = wxParams.links; //分享出去的連結
let title = wxParams.title; //分享的標題
let desc = wxParams.desc;
let imgUrl = wxParams.shareImage;
let shareSuccess = wxParams.shareSuccess;
let shareFailure = wxParams.shareFailure;
let configFailure = wxParams.configFailure;
let resultObject = {
code: 0,
msg: ""
};
wx.config({
debug: false,
appId: r.appId,
timestamp: r.timestamp,
nonceStr: r.nonceStr,
signature: r.signature,
jsApiList: [
'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone'
]
});
wx.ready(function() {
wx.onMenuShareTimeline({
title: title, // 分享標題
desc: desc, // 分享描述
link: links, // 分享連結
imgUrl: imgUrl, // 分享圖示
success: function() {
if(shareSuccess) {
shareSuccess("Timeline");
}
},
cancel: function() {
if(shareFailure) {
shareFailure(resultObject);
}
}
});
//微信分享選單測試
wx.onMenuShareAppMessage({
title: title, // 分享標題
desc: desc, // 分享描述
link: links, // 分享連結
imgUrl: imgUrl, // 分享圖示
success: function() {
if(shareSuccess) {
shareSuccess("AppMessage");
}
},
cancel: function() {
if(shareFailure) {
shareFailure(resultObject);
}
}
});
wx.onMenuShareQQ({
title: title, // 分享標題
desc: desc, // 分享描述
link: links, // 分享連結
imgUrl: imgUrl, // 分享圖示
success: function() {
if(shareSuccess) {
shareSuccess("QQ");
}
},
cancel: function() {
if(shareFailure) {
shareFailure(resultObject);
}
}
});
wx.onMenuShareWeibo({
title: title, // 分享標題
desc: desc, // 分享描述
link: links, // 分享連結
imgUrl: imgUrl, // 分享圖示
success: function() {
if(shareSuccess) {
shareSuccess("Weibo");
}
},
cancel: function() {
if(shareFailure) {
shareFailure(resultObject);
}
}
});
wx.onMenuShareQZone({
title: title, // 分享標題
desc: desc, // 分享描述
link: links, // 分享連結
imgUrl: imgUrl, // 分享圖示
success: function() {
if(shareSuccess) {
shareSuccess("QZone");
}
},
cancel: function() {
if(shareFailure) {
shareFailure(resultObject);
}
}
});
});
wx.error(function(res) {
if(configFailure) {
configFailure(resultObject);
}
// Vue.$showError();
// config資訊驗證失敗會執行error函式,如簽名過期導致驗證失敗,具體錯誤資訊可以開啟config的debug模式檢視,也可以在返回的res引數中檢視,對於SPA可以在這裡更新簽名。
});
}
4.頁面呼叫
import { wxShare } from './wxapi.js'
methods: {
share() {
let params = {
"body": {
ChatShareUrl: window.location.href
}
}
this.$api.post('weChatShare', params, r => {
wxShare(r, {
shareSuccess: this.shareSuccess,
links: process.env.SHARE_ROOT,
title: "分享標題",
desc: '分享描述',
shareImage: process.env.SHARE_ROOT_IMG + '/static/images/share.png',
shareFailure: function() {
this.showToast("分享失敗,您取消了分享!")
},
configFailure: function() {
this.showToast("微信接口出現異常,請稍後再試!")
}
});
});
}
},
created() {
this.share()
}
}