2024前端面试题vue篇 Vue Router 如何配置 404 页面(2)
今儿面试vue又遇到这道题了。
面试官:你好,请说说Vue Router 如何配置 404 页面
我答:这题正好我会,(看来面试前看刷题没错)
在 Vue Router 中配置 404 页面(也就是所谓的路由未找到时的页面),你通常会使用通配符路由(* 或 /:pathMatch(.*)*)来捕获所有未匹配到具体路由的路径。这种路由应该放在所有具体路由之后,以确保只有在没有其他路由匹配时才会使用它。
面试官:可以哟!
代码示例:
import Vue from 'vue';
import Router from 'vue-router';
import HomePage from './views/HomePage.vue';
import NotFoundPage from './views/NotFoundPage.vue'; // 假设你有一个 NotFoundPage.vue 组件
Vue.use(Router);
export default new Router({
mode: 'history', // 或者 'hash'
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: HomePage
},
{
path: '/about',
name: 'about',
// 假设你有一个 AboutPage.vue 组件
component: () => import('./views/AboutPage.vue')
},
// 其他具体的路由...
// 最后添加通配符路由
{
path: '*', // 或者 '/:pathMatch(.*)*' 也可以,但 '*' 更简洁
name: 'not-found',
component: NotFoundPage
}
]
});
NotFoundPage.vue 是自定义的 404 页面组件。当访问的 URL 不匹配任何已定义的路由时,Vue Router 就会渲染这个 NotFoundPage 组件。
注意,路由配置的顺序很重要。通配符路由(*)必须放在最后,以确保它只会在没有其他路由匹配时才会被使用。
面试官:这题算你过