1.授权登录
main.js
router.beforeEach((to, from, next) => {
const token = localStorage.getItem('token');
const openid = localStorage.getItem('openid');
// console.log("token",token,"openid",openid);
if (!openid) {
// console.log("path",to.path);
if (to.path == '/Auth') {
next()
} else if(token){
next()
}
}else{
next()
}
})
auth.vue
<template>
<div>
</div>
</template>
<script>
const murl = 'http://***'; //与公众平台里配置的一致
const url = localStorage.getItem("now_url");
export default {
//生命周期函数
created() {
const code = this.GetUrlParame('code'); // 截取code
const state = this.GetUrlParame('state'); // 截取code
if (!code) {
let redirectUrl = encodeURIComponent(murl);
let WX_APPID = 'wx8baaff86779e06da';
let oAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WX_APPID}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=bc17befd6d5060f16de95e38f6eaf69c&connect_redirect=1#wechat_redirect`
window.location.href = oAuthUrl;
} else {
let _this = this;
_this.$http.post(_this.$http.getCode,
_this.$qs.stringify({
code: code,
state: state
}),
{
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}
).then(response => {
// console.log(response.code,response);
if(response.code==1){
window.localStorage.setItem('token', response.data.token);
sessionStorage.setItem('currIndex', 0);
_this.$router.push({
path: "/"
});
}else if(response.code==2){
_this.$toast(response.msg);
// console.log("222",response.code);
window.localStorage.setItem('openid', response.data.wx_openid);
// console.log(typeof(response.data)