目录

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

问题描述

原因分析:

解决方案:


项目场景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&gt; = [
  {
    path: '/',
    name: 'home',
    component: () =&gt; 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;

 

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注