Vue-Router的20道基础面试题


以下是 Vue Router 的20道基础面试题,附带简洁答案和解释,助你系统掌握这部分知识:


1. Vue Router 是什么?

答: Vue.js 的官方路由管理器,实现前端单页面应用(SPA)的页面导航。


2. 如何在 Vue 项目中安装和使用 Vue Router?

答:

npm install vue-router

在主入口引入并配置:

import { createRouter, createWebHistory } from 'vue-router';
const routes = [...];
const router = createRouter({
  history: createWebHistory(),
  routes
});
app.use(router);

3. Vue Router 中 history 模式和 hash 模式区别?

答:

  • hash 模式 URL带#,兼容性好,无需服务器配置。
  • history 模式URL干净,支持前进后退,需服务器配置404重定向。

4. 如何定义路由配置?

答:

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
];

5. Vue Router 中的路由参数有哪些类型?

答:

  • 动态参数(如 /user/:id
  • 查询参数(?key=value
  • 星号通配符参数(如 *

6. 如何在组件中获取动态路由参数?

答:

this.$route.params.id

7. 如何编程式导航?

答:

this.$router.push('/home');
this.$router.replace('/home');

8. 什么是嵌套路由?如何配置?

答: 路由中的子路由,父组件通过 <router-view> 渲染子路由组件。

{
  path: '/user',
  component: User,
  children: [
    { path: 'profile', component: UserProfile }
  ]
}

9. 路由懒加载怎么实现?

答: 使用动态导入 import()

const Home = () => import('./components/Home.vue');

10. 什么是导航守卫?有哪几种?

答: 用于拦截路由跳转,做权限验证等。

  • 全局前置守卫 router.beforeEach
  • 全局后置守卫 router.afterEach
  • 路由独享守卫 beforeEnter
  • 组件内守卫 beforeRouteEnterbeforeRouteLeavebeforeRouteUpdate

11. 如何取消路由跳转?

答: 在导航守卫中调用 next(false) 或抛出错误。


12. Vue Router 如何处理404页面?

答: 配置通配符路由:

{ path: '/:pathMatch(.*)*', component: NotFound }

13. router-link 标签的作用?

答: 用于声明式导航,生成带链接的标签。


14. 如何传递查询参数?

答:

<router-link :to="{ path: '/search', query: { q: 'vue' } }">搜索</router-link>

15. 如何监听路由变化?

答:

watch: {
  '$route'(to, from) {
    // 处理变化
  }
}

16. props 如何传递给路由组件?

答:

{ path: '/user/:id', component: User, props: true }

17. 什么是 replacepush 的区别?

答:

  • push 添加新记录到历史栈
  • replace 替换当前历史记录

18. 如何实现路由跳转的滚动行为?

答:

const router = createRouter({
  scrollBehavior(to, from, savedPosition) {
    return savedPosition || { top: 0 };
  }
});

19. 什么是路由别名(alias)?

答: 允许同一路由配置多个访问路径。

{ path: '/user/:id', component: User, alias: '/u/:id' }

20. Vue Router 支持哪些模式?

答:

  • hash 模式(默认)
  • history 模式
  • abstract 模式(非浏览器环境)

讲解 Vue Router 的路由守卫及应用场景

2025年主流五大知名浏览器及其内核

评 论
请登录后再评论