vue2.0 如何在hash模式下实现微信分享

最近又把vue的demo拿出来整理下,正好要做“微信分享”功能,于是遇到新的问题;

由于hash模式下,带有“#”,导致微信分享的签证无效;当改成history的模式后,分享ok;

但是问题来了,history模式下相当操蛋:

刷新页面,页面报错404;这不是扯犊子吗?【不过这个问题,可以在后台解决,这里就不说了】

assets下的img文件,引入路径失败;

对于上面的问题,我是直接不能忍啊,所以history模式是肯定不行的;我决定依旧用hash模式;history模式万万要不得

那么问题来了:怎么在hash模式下实现微信分享?

其实微信分享失败的问题,最重要的一步就是解决“#”的问题;

一般的页面,我们获取当前的url是酱紫操作的

let params = '&params=' + JSON.stringify({url: window.location.href});

SPA页面,我们需要做点小调整,调整的目的是让“#”say goodbye

let params = '&params=' + JSON.stringify({url: encodeURIComponent(window.location.href.split('#')[0])});

这样修改后,签名的url中没带“#”,这样就ok了,下面贴上完成的代码

<script> // 微信分享 import configModel from "../models/config.model"; import elementService from "../services/element.service"; class ShareService{ wxShare(succCb, cancelCb, errorCb){ let baseUrl = 'http://q.letwx.com/api/jsapi?action=jscfg'; let samekey = '&uid=' + configModel.uid + '&wxapiopenid=' + configModel.apiopenid + '&wxapitoken=' + configModel.apitoken + '&debug=nf'; let params = '&params=' + JSON.stringify({url: encodeURIComponent(window.location.href.split('#')[0])}); // 这里是关键 let url = baseUrl + params + samekey; $.post(url, data => { elementService.loadingHide(); console.log(data); switch (data.error) { case 0: this.wxConfig(data.cfg, configModel.shareInfo, succCb, cancelCb, errorCb); break; default: elementService.message(data.error_msg, 'error'); break; } }, 'json'); } wxConfig(wxconfig, share, succCb, cancelCb, errorCb){ wx.config({ debug: false, appId: wxconfig.appId, timestamp: wxconfig.timestamp, nonceStr: wxconfig.nonceStr, signature: wxconfig.signature, jsApiList: [ 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo' ] }); wx.ready(function() { wx.onMenuShareAppMessage({ //朋友 title: share.title, desc: share.desc, link: share.link, imgUrl: share.imgUrl, success: function() { succCb && succCb(); }, cancel: function() { cancelCb && cancelCb(); } }); wx.onMenuShareTimeline({ //朋友圈 title: share.desc, link: share.link, imgUrl: share.imgUrl, success: function() { succCb && succCb(); }, cancel: function() { cancelCb && cancelCb(); } }); wx.onMenuShareQQ({ //QQ title: share.title, desc: share.desc, link: share.link, imgUrl: share.imgUrl, success: function() { succCb && succCb(); }, cancel: function() { cancelCb && cancelCb(); } }); wx.onMenuShareWeibo({ //QQ title: share.title, desc: share.desc, link: share.link, imgUrl: share.imgUrl, success: function() { succCb && succCb(); }, cancel: function() { cancelCb && cancelCb(); } }); }); wx.error(function(res) { console.log(res); errorCb && errorCb(JSON.stringify(res)); }); } } let shareSerivice = new ShareService(); export default shareSerivice; </script>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/a536996f51f799ef3c20a757a1a72a14.html