在UniApp中,我们可以通过编写一个登录拦截器来实现未登录时点击其他地方跳转到登录页的功能。本文将详细介绍如何实现这个功能。
uni.addInterceptor拦截器
uni.addInterceptor拦截器是uni-app官网提供的拦截器,可以利用它来实现登录拦截器,用户在没有登录时是不能进行其他操作。链接:https://uniapp.dcloud.net.cn/api/interceptor.html#addinterceptor
1.首先在根目录下新建一个文件夹components(昵称任意)。在components文件夹下建一个interceptor.js。
2.在interceptor.js中写入
// 页面白名单,不受拦截
const whiteList = [
'/pages/index/index',
'/pages/class/class',
'/pages/release/release',
'/pages/mine/mine'
]
function hasPermission (url) {
let islogin = uni.getStorageSync('isLogin');//在这可以使用token,isLogin是登录成功后在本地存储登录标识
islogin = Boolean(Number(islogin));//返回布尔值
// 在白名单中或有登录判断条件可以直接跳转
if(whiteList.indexOf(url) !== -1 || islogin) {
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.登录页面,登录成功时在本地存一个唯一标识符:“isLogin”
uni.setStorageSync('isLogin',1);//用于登录拦截判断
4.在main.js中引用。
import '@/components/Interceptor.js';//引入拦截
这就可以实现一个简单的登录拦截器啦!!