項目需求: 對每個單頁面進行微信分享的標題 描述 縮略圖和鏈接設置
1:引入微信sdk文件 安裝依賴
npm install weixin-js-sdk --save
2:在assets下新建一個js文件 wx_share.js
import axioss from 'axios'
import wx from 'weixin-js-sdk' //微信sdk依賴
const jsApiList = ['onMenuShareAppMessage', 'onMenuShareTimeline', 'onMenuShareQQ','onMenuShareWeibo']
//要用到微信AP
//
export function getJSSDK(dataForWeixin) {
let gourl = window.location.href.split("#")[0];
let reqData = {};
reqData.gourl = gourl;
axioss.get('http://weixin.yizijob.com/activity/gotoPage.do' , {
params:reqData
}).then(res => {
console.log(res)
wx.config({
debug: false, // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時纔會打印。
//下面這裏不用管 讓後臺看一下 讓他返給你
appId: 'wxc6f2e83fc1f53576', // 必填,公衆號的唯一標識
timestamp: res.data.content.timestamp, // 必填,生成簽名的時間戳
nonceStr: res.data.content.nonceStr, // 必填,生成簽名的隨機串
signature: res.data.content.signature, // 必填,簽名
jsApiList: [
'onMenuShareAppMessage',
'onMenuShareQQ'
] // 必填,需要使用的JS接口列表
})
console.log(res) //打印測試
wx.ready(function () {
wx.onMenuShareAppMessage({
title: dataForWeixin.title,
desc: dataForWeixin.desc,
link: dataForWeixin.linkurl,
imgUrl: dataForWeixin.img,
trigger: function trigger(res) { },
success: function success(res) {
console.log('已分享');
},
cancel: function cancel(res) {
console.log('已取消');
},
fail: function fail(res) {
//alert(JSON.stringify(res));
}
});
// 2.2 監聽“分享到朋友圈”按鈕點擊、自定義分享內容及分享結果接口
wx.onMenuShareTimeline({
title: dataForWeixin.title,
link: dataForWeixin.linkurl,
imgUrl: dataForWeixin.img,
trigger: function trigger(res) {
// alert('用戶點擊分享到朋友圈');
},
success: function success(res) {
//alert('已分享');
},
cancel: function cancel(res) {
//alert('已取消');
},
fail: function fail(res) {
//alert(JSON.stringify(res));
}
});
// 2.3 監聽“分享到QQ”按鈕點擊、自定義分享內容及分享結果接口
wx.onMenuShareQQ({
title: dataForWeixin.title,
desc: dataForWeixin.desc,
link: dataForWeixin.linkurl,
imgUrl: dataForWeixin.img,
trigger: function trigger(res) {
//alert('用戶點擊分享到QQ');
},
complete: function complete(res) {
//alert(JSON.stringify(res));
},
success: function success(res) {
//alert('已分享');
},
cancel: function cancel(res) {
//alert('已取消');
},
fail: function fail(res) {
//alert(JSON.stringify(res));
}
});
// 2.4 監聽“分享到微博”按鈕點擊、自定義分享內容及分享結果接口
wx.onMenuShareWeibo({
title: dataForWeixin.title,
desc: dataForWeixin.desc,
link: dataForWeixin.linkurl,
imgUrl: dataForWeixin.img,
trigger: function trigger(res) {
//alert('用戶點擊分享到微博');
},
complete: function complete(res) {
//alert(JSON.stringify(res));
},
success: function success(res) {
//alert('已分享');
},
cancel: function cancel(res) {
//alert('已取消');
},
fail: function fail(res) {
//alert(JSON.stringify(res));
}
});
})
wx.error(function (res) {
//alert("微信驗證失敗");
});
})
}
3:在需要進行微信分享的vue頁面進行引入方法
import { getJSSDK } from "@/assets/js/wx_share.js"; // 微信分享
mounted(){
let obj = {
title: "my title", //分享標題
desc: 'my desc', //分享內容
linkurl: '##', //分享鏈接
img: "xxx.png", //分享內容顯示的圖片
}
getJSSDK(obj)
}