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 页面组件重新加载!!!

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐