export const authState = { state: { userId: undefined, token: undefined, }, login(data) { this.state.userId = data.userId this.state.token = data.token localStorage.setItem('auth', JSON.stringify({ "userId": this.state.userId, "token": this.state.token, })) }, logout() { this.state.userId = undefined this.state.token = undefined localStorage.removeItem('auth') }, isLogin() { if (this.state.userId == undefined) { const data = localStorage.getItem("auth") if (data) { this.login(JSON.parse(data)) return true } else { return false } } else { return true } } } export const loginPage = "/pages/coupons/index/index"; export const whitelist = [ "pages/coupons/coupon/index", "/pages/coupons/coupon/index", "pages/coupons/finish/index", "/pages/coupons/finish/index", ] export function checkPage(url = undefined){ if(url == undefined){ const pages = getCurrentPages() const currentPage = pages[pages.length - 1] url = currentPage.route } // console.log(url) if (url != loginPage && whitelist.findIndex((item)=>{return url == item}) == -1 && !authState.isLogin()) { uni.redirectTo({ url: loginPage }) uni.showToast({ title: "请登录", icon: "none" }) return false }else return true } export function initAuth() { const routeFnList = ["navigateTo", "redirectTo","reLaunch", "switchTab"] routeFnList.forEach(item => { // 添加拦截器 uni.addInterceptor(item, { invoke(e) { // 在跳转前做一些事情 return checkPage(e.url) checkPage(e.url) }, success(e) { // 在跳转成功后做一些事情 // console.log('跳转成功', e); }, fail(e) { // 在跳转失败后做一些事情 // console.log('跳转失败', e); }, complete(e) { // 在跳转结束后做一些事情 // console.log('跳转结束', e); } }); }) }