uniapp路由拦截封装
快速简单的使用uniapp提供的拦截方法uni.addInterceptor实现路由拦截
官网地址:https://uniapp.dcloud.net.cn/api/interceptor.html#addinterceptor
1、先建一个ts文件,内容如下
/**
* @description 自定义路由拦截
*/
// 白名单不需要登陆可见的
const whiteList = [
// '/', // 注意入口页必须直接写 '/'
'/pages/index',
'/pages/mall',
'/pages/login'
]
export function routingIntercept() {
const list = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab']
// 用遍历的方式分别为,uni.navigateTo,uni.redirectTo,uni.reLaunch,uni.switchTab这4个路由方法添加拦截器
list.forEach(item => {
uni.addInterceptor(item, {
invoke(e) {
// 获取要跳转的页面路径(url去掉"?"和"?"后的参数)
const url = e.url.split('?')[0]
// 判断当前窗口是白名单,或者已登录状态,如果是则不重定向路由
if (whiteList.indexOf(url) > -1 || uni.getStorageSync('userId')) {
return e
} else {
//重定向到登陆页面
e.url = '/pages/login'
return e
}
},
fail(err) {
// 失败回调拦截
console.log(err)
}
})
})
}
2、在app.vue里调用此方法
onLaunch(() => {
routingIntercept()
})