起因
微信分享网址时无法分享图片,这个问题需要用jssdk去解决。其实开始的时候时可以看到图片的,但后来微信禁止了。所以只能使用jssdk去解决。
普通网页开发很简单,但是使用vue或其他前端框架开发spa单页面webapp的时候就会有问题了。只要url发生变化就会报签名错误。其实微信官方上已经写了说明。
所有需要使用JS-SDK的页面必须先注入配置信息,否则将无法调用(同一个url仅需调用一次,对于变化url的SPA的web app可在每次url变化时进行调用,目前Android微信客户端不支持pushState的H5新特性,所以使用pushState来实现web app的页面会导致签名失败,此问题会在Android6.2中修复)。
但这些说明然并卵(然而并没有什么卵用)。
问题根源
1 同一个url仅需调用一次,对于变化url的SPA的web app可在每次url变化时进行调用
如果你的链接时采用hash方式,锚点变了也要重新调用,因为url发生了变化,这一点可以放在router的监听事件中比如watch一下$route,或者使用2.2 中引入的 beforeRouteUpdate 守卫。
2 生成签名时url中不能包含锚点
微信jssdk的签名是需要服务端来生成的,所以我们需要将当前页面的网址传递给服务端,由服务端生成wx.config初始化所需要的参数。
但是url传递的时候需要注意,一定一定一定不能带有锚点链接。可以使用location.href.split(‘#’)[0]获取url中锚点之前的部分。
比如你的网址是http://domain.com/index.html#/food/1
你只需要把http://domain.com/index.html传递到服务端,让服务端生成签名就可以了,你在调用jssdk的时候可以把url后面添加锚点链接。
实例
安装jssdk
npm install weixin-js-sdk –save
前段代码
export default {
mounted() {
this.$nextTick(function () {
this.getConfig()
})
},
data () {
return {
detail: [],
}
},
methods: {
// 微信分参数
getConfig() {
let url = location.href.split('#')[0] //获取锚点之前的链接
this.$http.get('/index.php',{
params: {
url: url
}
}).then(response => {
let res = response.data;
this.wxInit(res);
})
},
// 微信分享
wxInit(res) {
let url = location.href.split('#')[0] //获取锚点之前的链接
let links = url+'#/Food/' + this.$route.params.id;
let title = this.detail.name + '-嘌呤查';
let desc = '了解更多知识,请关注“嘌呤查”公众号';
let imgUrl = this.thumb;
wx.config({
debug: false,
appId: res.appId,
timestamp: res.timestamp,
nonceStr: res.nonceStr,
signature: res.signature,










