项目场景:客户要求用户在未登录的情况下,用户只可以在底部导航栏操作或是部分页面可操作,点击其他的的功能都要跳转到登录页面。
解决办法:uniapp官网推出的uni.addInterceptor()拦截器uni.addInterceptor(STRING, OBJECT) | uni-app官网 (dcloud.net.cn)
https://uniapp.dcloud.net.cn/api/interceptor.html#addinterceptor
1.实现步骤
(1)首先在根目录下新建一个文件夹(昵称任意)utils。在utils文件夹下建一个interceptor.js。
(2)在interceptor.js中写入,下面代码中的白名单数组whiteList中写入的页面路径是允许未登录也能访问的页面,简单来说就是写在whiteList中的页面路径就是可放行,否者就拦截让用户去登录。
// 页面白名单,不受拦截
const whiteList = [
'/pages/index/index',
'/pages/class/class',
'/pages/release/release',
'/pages/mine/mine'
]
function hasPermission (url) {
// token是登录成功后在本地存储登录标识,存储一个能够判断用户登录的唯一标识就行,根据自己存储的数据类型来判断
let token= uni.getStorageSync('token');
// 在白名单中或有登录判断条件可以直接跳转
if(whiteList.indexOf(url) !== -1 || token) {
console.log('跳转的页面在白名单内或是已登录')
return true
}
console.log('跳转的页面不在白名单内且未登录')
return false
}
uni.addInterceptor('navigateTo', {
// 页面跳转前进行拦截, invoke根据返回值进行判断是否继续执行跳转
invoke (e) {
if(!hasPermission(e.url)){
uni.reLaunch({
url: '/pages/login/login'
})
return false
}
return true
},
success (e) {
}
})
uni.addInterceptor('switchTab', {
// tabbar页面跳转前进行拦截
invoke (e) {
if(!hasPermission(e.url)){
uni.reLaunch({
url: '/pages/login/login'
})
console.log('跳转的页面在白名单内或是已登录')
return false
}
console.log('跳转的页面不在白名单内且未登录')
return true
},
success (e) {
}
})
(3)登录页面,登录成功时在本地存一个用户登录唯一标识符:“token”,用于拦截器判断用户是否登录。
// 用户登录时存个token 用于登录拦截判断
uni.setStorageSync('token', '后端返回的token');
(4)在main.js中引用。
import '@/utils/Interceptor.js';//引入拦截
注意!!!!注意!!!!注意!!!!
uni.addInterceptor() 拦截器不能拦截原生的底部导航栏。
两种情况及解决方案:
(1)自定义的底部导航栏:
直接使用uni.addInterceptor() 拦截器就可以实现全局拦截,(自定义的跳转方式要是uni.switchTab跳转方式)。
(2)pages.json原生的底部导航栏:
在tabbar页面onShow生命周期中判断是否登录实现tabbar页面的拦截,搭配uni.addInterceptor() 拦截非tabbar页面,实现全局拦截。
这就可以实现一个简单的登录拦截器啦,下课!!