Vue.js - 实现访问未定义路由时跳转至NotFound页面教程(404页面)
作者:hangge | 2026-09-02 08:44
在单页面应用(SPA)中,路由通常由前端(Vue Router)管理。当用户访问一个未定义的路由时,我们希望展示一个友好的 404 页面(NotFound 组件),提示“页面不存在”,并给出返回首页、搜索或上一步操作的选项。下面我将通过样例演示如何实现该功能。

1,添加 NotFound 页面的路由配置
在 src/router/index.js 文件中,添加 NotFound.vue 页面的路由配置,为 path 属性指定匹配所有页面的规则。注意:
- /:pathMatch(.*)* 是 Vue Router 4 推荐写法(而不是 *)。
- catch-all 路由必须放在 routes 数组最后,否则会抢占其它路由。
import Vue from "vue";
import VueRouter from "vue-router";
import HomeView from "../views/HomeView.vue";
import AboutView from "../views/AboutView.vue";
import NotFound from "../components/NotFound.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "home",
component: HomeView,
},
{
path: "/about",
name: "about",
component: AboutView,
},
// catch-all 404 路由 — 必须放最后
{
path: "/:pathMatch(.*)*",
name: "NotFound",
component: NotFound,
},
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes,
});
export default router;
2,新建 NotFound 页面
在 src/components 文件夹下新建 NotFound.vue 页面,代码如下。可以看到这里我们可以通过 $route.params.pathMatch 来获取路径参数值。
<template>
<div class="not-found" style="text-align:center; padding:40px;">
<h1>404</h1>
<h2>{{ $route.params.pathMatch }}页面未找到</h2>
<p>你要访问的页面不存在或已被移除。</p>
<div style="margin-top:20px;">
<button @click="goHome">返回首页</button>
<button @click="goBack" style="margin-left:8px;">返回上一页</button>
</div>
</div>
</template>
<script>
export default {
name: "NotFound",
methods: {
goHome() {
this.$router.push({ name: "home" }).catch(() => { })
},
goBack() {
window.history.length > 1 ? this.$router.back() : this.$router.push({ name: "Home" })
}
}
}
</script>
3,运行测试
(1)使用浏览器访问一个没有注册过的路径地址,可以看到页面上会显示 NotFound.vue 页面内容和对应路径参数值。

(2)点击 NotFound 页面上的“返回首页”按钮则会跳回到首页。

全部评论(0)