参考:uniapp 使用 addInterceptor 实现登录拦截

    1. import store from "../store";
    2. const whiteList = [
    3. // "/pages/myInfo/myInfo"
    4. ];
    5. //白名单 不需要登录的页面路径组成的数组
    6. function hasPermission(url) {
    7. // 在白名单中或有token,直接跳转
    8. if (whiteList.indexOf(url) !== -1 || store.state.user.token) {
    9. return true;
    10. }
    11. return false;
    12. }
    13. uni.addInterceptor("navigateTo", {
    14. // 页面跳转前进行拦截, invoke根据返回值进行判断是否继续执行跳转
    15. invoke(e) {
    16. if (!hasPermission(e.url)) {
    17. uni.reLaunch({
    18. url: "/pages/myInfo/login",
    19. });
    20. return false;
    21. }
    22. return true;
    23. },
    24. success(e) {
    25. // console.log(e)
    26. },
    27. });
    28. uni.addInterceptor("switchTab", {
    29. // tabbar页面跳转前进行拦截
    30. invoke(e) {
    31. if (!hasPermission(e.url)) {
    32. uni.reLaunch({
    33. url: "/pages/myInfo/login",
    34. });
    35. return false;
    36. }
    37. return true;
    38. },
    39. success(e) {
    40. // console.log(e)
    41. },
    42. });