返回
Vue-Router的面试题及答案汇总
前端
2023-09-13 19:19:02
Vue-Router 面试题汇总
1. 怎么重定向页面?
第一种:
// 在组件中使用 this.$router.push('/login')
// 在组件中使用 this.$router.replace('/login')
第二种:
// 在路由配置中使用 redirect 属性
{
path: '/home',
redirect: '/login'
}
第三种:
// 在路由配置中使用 beforeEach 钩子函数
router.beforeEach((to, from, next) => {
if (to.path === '/home') {
next('/login')
} else {
next()
}
})
2. 怎么配置404页面?
// 在路由配置中使用 catch-all 路由
{
path: '*',
component: NotFoundComponent
}
3. 路由两种模式的区别
哈希模式:
- 使用 URL 的哈希部分来存储路由信息,如
#/home
。 - 兼容所有浏览器,包括不支持 HTML5 History API 的浏览器。
- 需要在服务器端配置,以便将所有请求重定向到
/index.html
。
历史模式:
- 使用 URL 的路径部分来存储路由信息,如
/home
。 - 需要浏览器支持 HTML5 History API。
- 不需要在服务器端配置,但需要确保服务器能够为所有路由提供正确的 HTML 页面。
4. 动态路由怎么传参?
// 在路由配置中使用 params 属性
{
path: '/user/:id',
component: UserComponent
}
// 在组件中使用 this.$route.params.id 获取参数
5. 怎么监听路由变化?
// 使用 Vue Router 的 $route 对象
this.$route.params.id // 获取参数
this.$route.path // 获取路径
this.$route.query // 获取查询参数
// 使用 Vue Router 的 $router 对象
this.$router.currentRoute // 获取当前路由
this.$router.push('/login') // 跳转到登录页
this.$router.replace('/login') // 替换当前路由
6. 怎么使用路由钩子函数?
// 全局钩子函数
router.beforeEach((to, from, next) => {
// ...
})
// 组件钩子函数
export default {
beforeRouteEnter(to, from, next) {
// ...
},
beforeRouteUpdate(to, from, next) {
// ...
},
beforeRouteLeave(to, from, next) {
// ...
}
}
7. Vue-Router 中的懒加载怎么实现?
// 在路由配置中使用懒加载组件
{
path: '/user',
component: () => import('./UserComponent.vue')
}
8. Vue-Router 中的嵌套路由怎么实现?
// 父路由
{
path: '/user',
component: UserComponent,
children: [
{
path: 'detail',
component: UserDetailComponent
}
]
}
// 子路由
{
path: '/user/detail',
component: UserDetailComponent
}
9. Vue-Router 中的命名路由怎么实现?
// 在路由配置中使用 name 属性
{
path: '/user',
name: 'user',
component: UserComponent
}
// 在组件中使用 this.$router.push({ name: 'user' }) 跳转到命名路由
10. Vue-Router 中的编程式导航怎么实现?
// 使用 this.$router.push('/login') 跳转到登录页
// 使用 this.$router.replace('/login') 替换当前路由
// 使用 this.$router.go(-1) 返回上一页
// 使用 this.$router.go(1) 前进一页
总结
本文总结了Vue-Router面试中经常出现的问题和答案,涵盖了路由、组件、导航、钩子、重定向、404页面、哈希模式和历史模式等方面的内容,希望对您有所帮助。