什么是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"})} |
|
来自: wintelsui > 《好好学 Web 开发》