Vue3实现当访问的路由不存在时跳转到404页面的方法详解

Vue3实现当访问的路由不存在时跳转到404页面的方法详解


一、前言

在 Vue 3 中,你可以使用 Vue Router 来实现当访问的路由不存在时跳转到 404 页面。以下是详细的方法:

1. 创建 404 组件

首先,你需要创建一个用来显示 404 错误的组件。例如,你可以创建一个 NotFound.vue 组件来展示 404 错误页面的内容。

<template>
  <div>
    <h1>404 Not Found</h1>
    <p>Sorry, the page you are looking for does not exist.</p>
  </div>
</template>

<script>
export default {
  name: 'NotFound'
}
</script>

2. 配置路由

接下来,在 Vue Router 的路由配置中,你需要添加一个通配符路由来捕获所有未匹配的路径,并将其指向 404 组件。

import { createRouter, createWebHistory } from 'vue-router';
import NotFound from './components/NotFound.vue';

const routes = [
  // 其他路由
  // ...

  // 404 路由,放在最后
  { path: '/:pathMatch(.*)', component: NotFound },
];

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

export default router;

在这个例子中,我们使用了通配符路由 /:pathMatch(.*) 来捕获所有未匹配的路径,并将其指向 404 组件 NotFound。确保将这个通配符路由放在路由配置的最后,这样它才能捕获所有未匹配的路径。

3. 使用 router-link

最后,在你的应用中,你可以使用 router-link 组件来创建导航链接。当用户访问了一个不存在的路由时,他们将被重定向到 404 页面。

<template>
  <div>
    <router-link to="/">Home</router-link>
    <router-link to="/about">About</router-link>
    <router-link to="/non-existent-page">Non-Existent Page</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
}
</script>

通过以上的步骤,你就可以在 Vue 3 中实现当访问的路由不存在时自动跳转到 404 页面。

最近更新

  1. TCP协议是安全的吗?

    2024-06-08 19:14:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-08 19:14:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-08 19:14:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-08 19:14:02       20 阅读

热门阅读

  1. 设计模式 —— 装饰器模式

    2024-06-08 19:14:02       8 阅读
  2. 深度学习-10-测试

    2024-06-08 19:14:02       8 阅读
  3. git 怎么让一个文件不提交

    2024-06-08 19:14:02       8 阅读
  4. 算法题 — 可可喜欢吃香蕉(二分查找法)

    2024-06-08 19:14:02       10 阅读
  5. PostgreSQL的内存结构

    2024-06-08 19:14:02       9 阅读
  6. git版本管理工具

    2024-06-08 19:14:02       17 阅读
  7. 动态语言的开源编译器汇总

    2024-06-08 19:14:02       10 阅读
  8. Oracle 收缩表高水位线

    2024-06-08 19:14:02       8 阅读