vue3中404页面显示问题Catch all routes (“*“) must now be defined using a param with a custom regexp.

目录

项目场景:vue3,路由,404页面

问题描述

原因分析:

解决方案:

使用/:pathMatch(.*)或者/:catchAll(.*)

此图片用来封面引流的,前面不看都行,解决方案,点我点我


项目场景:vue3,路由,404页面

vue3项目中404页面的显示


问题描述

Catch all routes ("*") must now be defined using a param with a custom regexp.

当访问url时,访问没有配置的路由时,默认显示404页面,浏览器报错

 

import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: () => import('../layout/layout.vue'),
    children: [
      {
        path: 'about', // 这里不要加上/about,使用就找不到页面
        name: 'about',
        component: () => import('../views/AboutView.vue'),
      },
    ],
  },
  {
    path: '*',
    redirect: '/404',
    children: [
      {
        path: '/404', // 这里要加上/404,和上面的redirect对应,必须加上/
        name: '404',
        component: () => import('../views/404/404.vue'),
      },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

export default router;

原因分析:

当捕获*所有的路由时,需要使用正则表达式的参数来表示


解决方案:

使用/:pathMatch(.*)或者/:catchAll(.*)

import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: () => import('../layout/layout.vue'),
    children: [
      {
        path: 'about', // 这里不要加上/about,使用就找不到页面
        name: 'about',
        component: () => import('../views/AboutView.vue'),
      },
    ],
  },
  {
    path: '/:pathMatch(.*)',
    redirect: '/404',
    children: [
      {
        path: '/404', // 这里要加上/404,和上面的redirect对应,必须加上/
        name: '404',
        component: () => import('../views/404/404.vue'),
      },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

export default router;

上面的方法会报一个警告:

之前的children里面需要加上'/'的问题解决,把children里面提出来

import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: () => import('../layout/layout.vue'),
    children: [
      {
        path: 'about', // 这里不要加上/about,使用就找不到页面
        name: 'about',
        component: () => import('../views/AboutView.vue'),
      },
    ],
  },
  {
    path: '/404',
    name: '404',
    component: () => import('../views/404/404.vue'),
  },
  {
    path: '/:pathMatch(.*)',
    redirect: '/404',
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

export default router;

此图片用来封面引流的,前面不看都行,解决方案,点我点我

 

猜你喜欢

转载自blog.csdn.net/qq_54455551/article/details/129236827