const baseurl = "//xxx" // 解析url參數並獲取code function getUrlParam(name) { //name爲要獲取的參數名 var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var rrr = decodeURIComponent(window.location.search); var r = rrr.substr(1).match(reg); if(r != null) return unescape(r[2]); return null; } // 請求微信服務器獲取code 方法 function getUserCode() { redirectURL = encodeURI((baseurl + window.location.pathname + window.location.search).split('&code')[0]);//獲取地址 const base = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='; let state; let surl; let reserveUrl; let appid = ""; let scope = "1"; window.location.href =base + appid +'&redirect_uri='+ redirectURL +'&response_type=code&scope='+ scope + '#wechat_redirect'; } // 路由變化時 router.beforeEach((to, from, next) => { //讀取sessionStorage的user let user = JSON.parse(sessionStorage.getItem('user')); //這裏能夠在開發生產環境下 加測試用戶信息存儲到sessionStorage if(document.domain == "127.0.0.1"){//本地環境 sessionStorage.setItem('user', JSON.stringify({ uid : 'eyJhbGciOiJIUzI1NiJ9.eyJ0IjoiNjY1NDA6MTU1NzQ0ODE2MiJ9.Dt4QHKq58GOdI_j8GhK0o3SkyWwHDlfeHR0nh1nEgsw', identity: 1 })); store.commit('updateUser', {"uid":"eyJhbGciOiJIUzI1NiJ9.eyJ0IjoiNjY1NDA6MTU1NzQ0ODE2MiJ9.Dt4QHKq58GOdI_j8GhK0o3SkyWwHDlfeHR0nh1nEgsw","user_id":66540,"identity":1,"avatar":"http://chaofenxiang.vip/data/attachment/avatar/1904/28/ef0b7277767425348af3503e0759eacd.png","nickname":"小義","sex":"女","mobile":"15070026795"});//賦值本地存儲 } // 已登陸 if (user) { next();//釋放路由 若是已經登陸 } // 未登陸 且不是在測試環境下 if (!user && document.domain != "127.0.0.1") { const code = getUrlParam('code');//獲取url 上面的code // 還未完成微信受權 if (!code) {//假如沒code getUserCode();//請求微信服務器獲取code } // 已完成微信受權 假如已經獲取到了code if (code) { //使用code 去登陸 axios.get("/xxxx", {// params: { code: code, } }).then(res => { if (res.status == 200) { let userInfo = res.data.userInfo; sessionStorage.setItem('user', JSON.stringify(userInfo));// 存sessionStorage next(); } else { } }).catch(err => { //登陸失敗,請刷新重試 }); } }else{ next(); } }); //ps 代碼放在main.js 裏面僅供參考