
uniapp通过addInterceptor拦截路由跳转,控制页面是否需要登录
uniapp通过addInterceptor拦截路由跳转,控制页面是否需要登录
·
通过addInterceptor拦截跳转,在页面跳转之前判断是否需要登录
App.vue:
import store from '@/store'
export default {
onLaunch: function() {
if(process.env.NODE_ENV !== 'development'){
console.log=()=>{
return ''
}
}
// const noLogin=['/mime/index/index']//不需要登录的页面
const noLogin=[]//不需要登录的页面
let setIntervalL=null
let curPage = null//当前页面
let curPageData=null//当前页面数据
// 登录方法
const xcxLogin=()=>{
return store.dispatch('user/xcxLogin')
}
// 拦截器方法
const addInterceptorFN=(item,url=null)=>{
// 路由拦截
const routerObject={
invoke(args) {
// 没有url,禁止跳转
if(!args.url){
return false;
}
let url=args.url.split('?')[0]
let notNeed=noLogin.includes(url)
// 初始换页面进入的,登录后刷新页面
if(args.isLaunch){
// 第一种刷新页面
uni.reLaunch({
url:args.url
})
// 第二种刷新页面
// curPage.data=curPageData
// if(curPage.onLoad)curPage.onLoad(curPage.options) // 传入参数
// if(curPage.onShow)curPage.onShow()
// if(curPage.onReady)curPage.onReady()
return false;
}
// 不需要验证登录
if(notNeed){
return true
}else{
// 没有登录
uni.hideLoading()
if(!store.state.user.userInfo || Object.keys(store.state.user.userInfo).length==0){
// 小程序自动登录
// 登录后重新跳转
if(!notNeedLoding){
uni.showLoading({
title:'登录中'
})
}
xcxLogin().then(res=>{
uni.hideLoading()
// 继续跳转
uni[item]({
url:args.url
})
}).catch((err)=>{
uni.hideLoading()
console.log('登录失败',err)
})
return false
}else{
return true
}
}
}
}
// 初始化,会将当前的路由传过来,然后验证
if(url){
routerObject.invoke({url:url,isLaunch:true})
}
// uniapp 拦截器
uni.addInterceptor(item,routerObject)
}
// 初始化拦截
const initPage=()=>{
let pages=getCurrentPages()
curPage=pages[pages.length-1]
if(curPage){
curPageData=curPage.data
// 页面加载完成后
if(setIntervalL)clearInterval(setIntervalL)
// 登录
let url=curPage.$page.fullPath
url=url.substr(0,1)=='/'?url:('/'+url)
let urlThis=url.split('?')[0]
let notNeed=noLogin.includes(urlThis)
let isReLaunch=false
// 没有登录过,需要登录后刷新页面
if(!store.state.user.userInfo || Object.keys(store.state.user.userInfo).length==0){
isReLaunch=true
}
if(!notNeed){
uni.hideLoading()
if(isReLaunch){
uni.showLoading({
title:'登录中'
})
}
xcxLogin().then(res=>{
uni.hideLoading()
if(isReLaunch){
addInterceptorFN('reLaunch',url)
}
}).catch((err)=>{
uni.hideLoading()
console.log('登录失败',err)
})
}
}
}
// 第一次进入
setIntervalL=setInterval(()=>{
initPage();
},100)
const addInterceptor=['navigateTo','redirectTo','reLaunch','switchTab']
addInterceptor.forEach(item=>{
// 挂载拦截器
addInterceptorFN(item)
})
},
onShow: function() {
console.log('App Show')
},
onHide: function() {
console.log('App Hide')
},
}
效果:
更多推荐
所有评论(0)