uniapp路由拦截

182 阅读1分钟

别使用它来进行登录时的路由拦截,这个路由拦截是假拦截,只是监听,我做的只是跳过去又跳到另外的地方

import { useUserInfoStore } from "@/stores/userInfoStore.js";
export default async function routingIntercept() {
  //需要拦截的路由
  const interceptLsit = [
    "backbutton",
    "/pages/index/index",
  ]; 
  //监听对象
  const list = [
    "navigateTo",
    "redirectTo",
    "reLaunch",
    "switchTab",
    "navigateBack",
  ];
  // 用遍历的方式分别为,uni.navigateTo,uni.redirectTo,uni.reLaunch,uni.switchTab这4个路由方法添加拦截器
  list.forEach((item) => {
    uni.addInterceptor(item, {
      invoke(e) {
        // 获取要跳转的页面路径(url去掉"?"和"?"后的参数)
        const url = e.url ? e.url.split("?")[0] : e.from;
        console.log(">>路由拦截执行", e, url);
        if (interceptLsit.includes(url)) {
            //自己处理,一般是switchTab就用switchTab跳
            //其他的用redirectTo
            //注意逻辑,不要陷入无限跳
        } else {
          console.log("其他直接放行", e);
          return e;
        }
      },
      fail(err) {
        // 失败回调拦截
        console.log(err);
      },
    });
  });
}