vue3 中动态添加路由出现的问题 [Vue Router warn]: No match found for location with path “xxx“

vue3 中动态添加路由出现的问题

引言

最近想尝试 vue3 + elementplus + axios + pinia 封装一个通用的后台模板,写到 vue-router 添加动态路由时,有一个不影响代码运行但是又有提示的报错,因此进行记录,方便大家进行解决

控制台提示

在这里插入图片描述
图片圈出的路由是动态加载的路由

解决方案

404等报错页面不再需要放在所有路由后面,可在一开始的时候就定义好报错跳转的页面路由。

页面之所有一开始报错找不到路由,是因为动态加载的路由在 beforeEach 的时候 to.matched 为空数组,即此时 next 跳转则会出现空白页面,之后使用 addRoute() 时动态添加的路由已经被加载上去,此时 next({ …to, replace: true }) 就跳转成功,所以需要在一开始先定义好 404 页面,防止路由报上面图片的错误

export const Layout = () => import("@/layout/index.vue");
export const constantRoutes = [
  {
    path: "/",
    redirect: "/dashboard",
    hidden: true,
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/login/index.vue"),
    hidden: true,
  },
  // 404页面
  {
    path: "/:pathMatch(.*)*",
    component: () => import("@/views/error/index.vue"),
    hidden: true,
  },
  {
    path: "/dashboard",
    component: Layout,
    redirect: "/dashboard/index",
    hidden: true,
    children: [
      {
        path: "index",
        name: "Dashboard",
        component: () => import("@/views/dashboard/index.vue"),
      },
    ],
  },
];

export default router;
import router, { resetRouter } from './router';
import { getToken } from '@/utils/sessionStorage';
import { usePermissionStore } from '@/store/permission';

// 判断是否初次或者刷新页面 0表示初次
let isRequest = 0;

router.beforeEach(async (to, _from, next) => {
  async function init () {
    // 调用方法获取路由
    const accessRoutes: any = await usePermissionStore().getGenerateRoutes();
    accessRoutes.forEach((route: any) => {
      router.addRoute(route);
    });
    isRequest = 1;
  }

  // 判断条件根据项目更改
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' });
    }
    if (isRequest) {
      next();
    } else {
      await init();
      next({ ...to, replace: true });
    }
  } else {
    sessionStorage.clear();
    isRequest = 0;
    if (to.path === '/login') {
      next();
    } else {
      resetRouter();
      next({ path: '/login' });
    }
  }
});

注意

vue2 中 通常使用 path: " * " 捕获所有路由,vue3 中不支持 vue2 的写法,需要用正则来捕获

1. /:pathMatch(.*)*  
2. /:pathMatch(.*)

上面两个的区别在于 如果省略最后一个'*'在解析或推送时将对params中的'/'字符进行编码

拓展

export const Layout = () => import("@/layout/index.vue");

// vue3 中,当有使用到动态加载路由的情况,使用这种方式引入会出现点击每个大导航栏,Layout 重新加载的情况,因此需要改成上面的写法
import Layout from "@/layout/index.vue";

在这里插入图片描述
点击用户管理中的任意路由之后,再点击个人信息中的任意路由,如果使用上面第二种写法,就会出现 Layout 页面组件重新加载!!!

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
出现"[Vue Router warn]: No match found for location with path "/" "这个警告时,它意味着当前路由没有与该路径匹配的路由。这通常是因为刷新浏览器时,动态路由尚未加载的原因。为了解决这个问题,我们可以采取以下两个步骤: 步骤1:在router/index.js文件,我们可以添加一个临时路由来处理当前路径的匹配问题。具体做法是: const { name } = router.currentRoute.value if (!name) { router.addRoute({ path: window.location.pathname, name: 'TempRoute', component: () => import('@/components/layouts/emptyLayout.vue') }) } 这样,在刷新浏览器时,就会在路由添加一个临时的路由来匹配当前路径。 步骤2: 确保在导出router实例之前,将临时路由添加路由。例如: export default router 通过以上两个步骤,我们可以解决"[Vue Router warn]: No match found for location with path "/" "这个警告,并且在刷新浏览器时正确地匹配相关的路由。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [vue3 addRoute 动态路由 页面刷新后 路由失效 [Vue Router warn]: No match found for location with path](https://blog.csdn.net/weixin_43835425/article/details/116708448)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [解决Vue3.0 页面刷新 [Vue Router warn]: No match found for location with path 警告](https://blog.csdn.net/maoeye283301717/article/details/126482974)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值