以vue项目为例
mounted() {
this.getCode()
},
methods: {
getCode() {
let t = this;
let local = window.location.href;
let appid = "**************"; // 公众号的appid
t.getUrlCode(local); // 截取code
if (t.code == null || t.code === "") {
// 如果没有code,则去请求
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
} else {
// 拿到code之后的操作
}
},
getUrlCode(url) {
let t = this;
// 截取url中的code方法
let length = url.indexOf("?");
let str = url.substring(length + 1);
let strs = str.split("&");
for (let i = 0; i < strs.length; i++) {
if (strs[i].split("=")[0] == "code") {
t.code = strs[i].split("=")[1];
}
}
}
}