uniapp 使用 addInterceptor 实现登录拦截

什么是uni.addInterceptor

uni.addInterceptor 是用于拦截 uni 的api的方法,一般用于给api添加全局的属性,或者全局处理事件

登录拦截 

使用 uni.interceptor ,实现当需要登录,并且没有token的时候跳转到登录页,否则正常跳转

import store from "../store";
const whiteList = [
  // "/pages/myInfo/myInfo"
];
//白名单 不需要登录的页面路径组成的数组

function hasPermission(url) {
  // 在白名单中或有token,直接跳转
  if (whiteList.indexOf(url) !== -1 || store.state.user.token) {
    return true;
  }
  return false;
}

uni.addInterceptor("navigateTo", {
  // 页面跳转前进行拦截, invoke根据返回值进行判断是否继续执行跳转
  invoke(e) {
    if (!hasPermission(e.url)) {
      uni.reLaunch({
        url: "/pages/myInfo/login",
      });
      return false;
    }
    return true;
  },
  success(e) {
    // console.log(e)
  },
});

uni.addInterceptor("switchTab", {
  // tabbar页面跳转前进行拦截
  invoke(e) {
    if (!hasPermission(e.url)) {
      uni.reLaunch({
        url: "/pages/myInfo/login",
      });
      return false;
    }
    return true;
  },
  success(e) {
    // console.log(e)
  },
});

补充,在h5模式下 浏览器 地址栏 输入地址切换路由 拦截

const needLoginList = [
    "path1",
    "path2"
]
let token= uni.getStorageSync("token")
let locationUrl = window.location.split("/#")[1]
if(needLoginList.includes(locationUrl)&&!token){
    uni.navigateTo({
        url:"loginPath"
    })

}

  • 7
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值