微信jssdk逻辑在vue中的运用详解

2020-06-14 06:18:24易采站长站整理

const wechatShareConfig = getWechatShareConfig(this);
if (wechatShareConfig) {
share({ ...wechatShareConfig });
}
}
};

export default wechatShareMixin;


// utils/lib/wechat/share
import { getTicket } from '@/utils/lib/wechat/helper'; // 签名接口
import { initSdk } from '@/utils/lib/wechat/config';
import sdk from 'weixin-js-sdk';

// 接口清单
const JS_API_LIST = ['onMenuShareAppMessage', 'onMenuShareTimeline'];

// 消息分享
function onMenuShareAppMessage(config) {
const { title, desc, link, imgUrl } = config;
sdk.onMenuShareAppMessage({ title, desc, link, imgUrl });
}

// 朋友圈分享
function onMenuShareTimeline(config) {
const { title, link, imgUrl } = config;
sdk.onMenuShareTimeline({ title, link, imgUrl });
}

export function share(wechatShareConfig) {
if (!wechatShareConfig.link) return false;

// 签名验证
getTicket(wechatShareConfig.link).then(res => {
// 初始化 `jssdk`
initSdk({
appid: res.appid,
timestamp: res.timestamp,
noncestr: res.noncestr,
signature: res.signature,
jsApiList: JS_API_LIST
});

sdk.ready(() => {
// 初始化目标接口
onMenuShareAppMessage(wechatShareConfig);
onMenuShareTimeline(wechatShareConfig);
});
});
}

写完之后乍一看似乎没什么毛病,但是每个 view 文件夹下的 .vue 都有一份微信配置显得很是臃肿,所以第二版实现则是将 jssdk 初始化放在 vue-router 的 beforeEach 钩子中进行,这样可以实现分享配置的统一配置,更加直观一些。


// router.js

//...
routes: [
{
path: '/',
component: Example,
meta: {
wechat: {
share: {
title: 'example',
desc: 'example desc',
imgUrl: 'http://huoche.7234.cn/images/jb51/ywtw1lav1mh.png'
}
}
}
}
]//...

// 初始化分享接口
function initWechatShare (config) {
if (config) {
share(config);
}
}

router.beforeEach((to, from, next) => {
const { shareConfig } = to.meta && to.meta.wechat;
const link = window.location.href;

if (!shareConfig) next();

initWechatShare({ ...shareConfig, link });
switchTitle(shareConfig.title); // 切换标题
next();
});

这样一来,会显得 .vue 清爽很多,不会有太多业务逻辑之外的代码。