封装一个工具js文件,写授权的方法,用Promise封装,可以异步获取到授权的结果
import axios from 'axios'
//获取url参数
function parse_url(url) {
// console.log('参数==>', url)
//定义函数
var pattern = /(\w+)=(\w+)/gi; //定义正则表达式
var parames = {}; //定义数组
url.replace(pattern, function (a, b, c) {
parames[b] = c;
});
return parames; //返回这个数组.
}
//UrlEncode函数
function urlencode(str) {
str = (str + "").toString();
return encodeURIComponent(str)
.replace(/!/g, "%21")
.replace(/'/g, "%27")
.replace(/\(/g, "%28")
.replace(/\)/g, "%29")
.replace(/\*/g, "%2A")
.replace(/%20/g, "+");
}
export default function WXauth() {
return new Promise((resolve, reject) => {
var url = decodeURI(window.location.href);
var params = parse_url(url);
var urls = urlencode(url);
if (!params.code) {
// alert("没有code");
location.href =
"https://open.weixin.qq.com/connect/oauth2/authorize?appid=vvvvv&redirect_uri=" +
urls +
"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&connect_redirect=1";
} else {
var url = decodeURI(window.location.href);
var params = parse_url(url);
var urls = urlencode(url);
axios.get('https:/xxxx/xxxx', {
params: {
code: params.code // 参数
}
}).then(res => {
const { data } = res.data
if (data.openid) {
localStorage.setItem("openid", data.openid);
localStorage.setItem("unionid", data.unionid);
localStorage.setItem("nickname", data.nickname);
localStorage.setItem("headimgurl", data.headimgurl);
resolve(res) // resolve结果
}
},
err => {
reject(err)
}).catch(error => {
reject(error)
})
}
})
}
路由表中beforeEach方法中判断,用户未授权时调用授权方法,.then中next()
import WXauth from '@/JS/auth.js'
import store from '@/store'
router.beforeEach((to, from, next) => {
nprogress.start()
if (!localStorage.getItem("openid")) {
console.log('未授权')
// 调用授权的方法
WXauth().then(res => {
if (res.data.code == 200) {
if (to.path === '/') {
console.log(2)
next()
} else {
next({
path: "/"
})
}
}
})
} else {
console.log('授权')
next()
}
})