原创文章,转载请注明原文章地址,谢谢!
第一步:vue端
1)App.vue类
import sdk from './router/share'; // 引入sdk.
mounted() {
/* eslint-disable */
const url = location.href.split('#')[0];
console.log(url)
const dataForWeixin = {
title: '分享标题', // 分享标题
desc: '分享内容', // 分享内容
linkurl: "http://nhh.ngrok.ibanzhuan.cn", // 分享链接
img: 'http://show.1m2.net/sj/static/img/sharre.jpg', // 分享内容显示的图片(图片必须是正方形的链接)
};
const ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) === 'micromessenger') {
sdk.getJSSDK(url,dataForWeixin); //传入sdk.js需要的参数
} else {
console.log('不是微信浏览器')
sdk.getJSSDK(url,dataForWeixin);
}
},
其中,title、desc、linkurl、img这四个为分享的设置,linkurl应动态获取当前前端页面地址
const dataForWeixin = {
title: '分享标题', // 分享标题
desc: '分享内容', // 分享内容
linkurl: "http://192.168.0.124", // 分享链接
img: 'http://show.1m2.net/sj/static/img/sharre.jpg', // 分享内容显示的图片(图片必须是正方形的链接)
};
2)share.js
import wx from 'weixin-js-sdk'
import axios from 'axios';
// 要用到微信API
function getJSSDK(url, dataForWeixin) {
// 调用后台接口换取参数
axios.get('http://nhc.ngrok.ibanzhuan.cn/app/wechat/initJSSDKConfig', {
params: {
url,
},
}).then((res) => {
console.log(res)
wx.config({
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: res.data.map.appid, // 必填,公众号的唯一标识
timestamp: res.data.map.timestamp, // 必填,生成签名的时间戳
nonceStr: res.data.map.nonceStr, // 必填,生成签名的随机串
signature: res.data.map.signature, // 必填,签名
jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline', 'updateAppMessageShareData', 'updateTimelineShareData','onMenuShareQQ','onMenuShareWeibo'] // 必填,需要使用的JS接口列表
});
wx.ready(function () {
wx.onMenuShareAppMessage({
title: dataForWeixin.title,
desc: dataForWeixin.desc,
link: dataForWeixin.linkurl,