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;

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

 

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值