首先吐槽下微信,vue项目在微信环境中不管是分享还是复制链接都是首页地址;比如用户打开首页home,然后点击跳转到A页面无分享页面,永远都是首页地址。这个坑查了多少资料啊,都没看到,更可气的是网上各种大佬博客都是一个方法:在static里面redirect.html文件,亲测没效果,也不知道是不是我的打开方式有问题。
后来让我眼前一亮看到了另一个文章,直觉告诉我这个可以,文章地址:https://juejin.im/post/5b8e44b3f265da433109ac4f。这个是可以的,感谢大佬。
为什么出现这个问题:ios下微信对于vue history模式不友好,分享的链接和复制链接都是第一次进来的地址,然后发现每次只有在A页面刷新之后才能解决这个问题。
解决方法:
利用vue的钩子方法router.beforeEach中来判断是否是ios设备,是的话用location.assign来刷新页面,这里千万不能用location.href和location.replace,亲测没用;
router.beforeEach((to, from, next) => {
var u = navigator.userAgent;
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
if (isiOS && to.path !== location.pathname) {
location.assign(to.fullPath)
} else {
next()
}
});接下来就是常规的微信分享操作,文档地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115。下面贴出代码:
新建weixinSdk.js:
npm intall weixin-js-sdk
import wx from 'weixin-js-sdk'
import {wechatShare} from "@/unit/global";
const jsApiList = ['updateAppMessageShareData', 'updateTimelineShareData']
function weixinShare(url, dataForWeixin) {
// wechatShare获取后台返回的签名等中重要参数信息,这里后台代码就不贴出来了
wechatShare(url).then(res => {
wx.config({
debug: false,
appId: res.data.appId,
timestamp: res.data.timestamp,
nonceStr: res.data.nonceStr,
signature: res.data.signature,
jsApiList: jsApiList
})
wx.ready(function () {
wx.updateAppMessageShareData({
title: dataForWeixin.title,
desc: dataForWeixin.desc,
link: dataForWeixin.link,
imgUrl: dataForWeixin.imgUrl,
success: function success(res) {
},
});
wx.updateTimelineShareData({
title: dataForWeixin.title,
link: dataForWeixin.link,
imgUrl: dataForWeixin.imgUrl,
success: function success(res) {
},
});
})
})
}
export default {
weixinShare: weixinShare
}在需要分享的页面中添加:
下面参数请自己配置或者获取
var obj = {
title: title,
desc: desc,
link: window.location.href.split('#')[0],
imgUrl: imgUrl,
}
sdk.weixinShare(link, obj)好了,搞定,让我停止了被boss叼,再次感谢大佬。

