vue开发微信分享的封装。
微信分享需要请求接口获取appId、签名等信息,vue单页模式下可以不需要每次打开页面都请求一次接口,可以结合store,将签名配置临时缓存。
必要导入(http.js是封装的axios拦截器,可参考:Vue axios拦截器_神圣的小昌哥的博客-CSDN博客)
import http from "./http.js"
import store from '../store/index'
import wx from "weixin-js-sdk"
微信分享配置
const weixinConfig = async () => {
var config = store.state.weixinConfig;
if (config.appId == "" || config.appId == null || config.appId == undefined) {
var url = location.href;
var index = url.indexOf("#");
if (index > 0) {
url = url.substring(0, index);
}
url = encodeURIComponent(url);
//同步请求接口获取签名
await http.get('https://www.xxx.com/Wxlogin/getsign', {
params: {
'url': url
}
}).then(data => {
config = data.data;
store.commit("setWeixinShareConfig",config);
})
}
//微信基本配置
wx.config({
debug: false,
appId: config.appId,
timestamp: config.timestamp,
nonceStr: config.nonceStr,
signature: config.signature,
jsApiList: [
'checkJsApi',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo'
]
});
}
store.mutations中记录相关配置签名
state: {
weixinConfig:{},
onWeixin: navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1,
},
mutations: {
setWeixinShareConfig(state,config){
state.weixinConfig = config;
}
},
分享方法
const weixinShare = async (share) => {
if(store.state.weixinConfig.appId == undefined){
await weixinConfig();
}
let {
shareLink,
shareTitle,
shareDescription,
shareImage
} = share;
//微信分享
if (!shareTitle) {
shareTitle = '默认分享标题';
}
if (!shareDescription) {
shareDescription = '默认分享简介';
}
if (!shareLink) {
//默认分享链接
shareLink = "https://www.baidu.com";
}
if (shareLink.indexOf("#") > 0) {
shareLink = window.location.href.split('#')[0] + '#' + window.location.href.split('#')[1]
}
if (!shareImage) {
//默认分享图标
shareImage = 'http://image.360eol.com/dd/images/home_03.png';
}
wx.ready(function() {
wx.onMenuShareTimeline({
title: shareTitle,
link: shareLink,
imgUrl: shareImage,
success: function() {},
cancel: function() {
// 用户取消分享后执行的回调函数
}
});
wx.onMenuShareAppMessage({
title: shareTitle,
desc: shareDescription,
link: shareLink,
imgUrl: shareImage,
type: '',
dataUrl: '',
success: function() {
},
cancel: function() {
// 用户取消分享后执行的回调函数
}
});
});
}
//导出
export {
weixinShare
}
页面导入、调用
import { weixinShare } from '@/utils/share'
//mounted中调用weixinShare()即可
mounted(){
weixinShare({
shareLink: location.href,
shareTitle: "分享标题分享标题分享标题分享标题",
shareDescription: "分享简介分享简介分享简介分享简介",
shareImage: "http://image.360eol.com/dd/images/home_03.png"
});
}