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 页面。