📚 Vue Router 4 核心知识点(Vue3技术栈)面试指南

154 阅读2分钟

大家好,我是鱼樱!!!

关注公众号【鱼樱AI实验室】持续每天分享更多前端和AI辅助前端编码新知识~~

今天给大家分享一个 Vue Router 路由面试准备,搞快点看下面就行!!!

一、安装与配置

npm install vue-router@4
 
// main.js
import { createApp } from 'vue'
import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  routes: []
})

const app = createApp(App)
app.use(router)

二、路由配置详解

1. 基本路由配置

 
const routes = [
  {
    path: '/',
    name: 'Home',
    component: HomeView
  }
]

2. 动态路由匹配

 
{
  path: '/user/:id',
  component: UserView
}
  • 获取参数:$route.params.id
  • 正则匹配::id(\d+) 匹配数字

3. 嵌套路由

 
{
  path: '/dashboard',
  component: Dashboard,
  children: [
    { path: 'profile', component: Profile }
  ]
}

4. 命名视图

 
<router-view name="header"/>
 
{
  path: '/',
  components: {
    default: Main,
    header: Header
  }
}

三、路由导航

1. 声明式导航

 
<router-link to="/about">About</router-link>
<router-link :to="{ name: 'user', params: { id: 123 }}">User</router-link>

2. 编程式导航

 
// 字符串路径
router.push('/users')

// 对象形式
router.push({ name: 'user', params: { id: '123' } })

// 替换当前位置
router.replace({ path: '/login' })

四、导航守卫

1. 全局守卫

 
router.beforeEach((to, from, next) => {
  // 权限验证逻辑
  next()
})

router.afterEach((to, from) => {
  // 页面统计逻辑
})

2. 路由独享守卫 beforeEnter

 
{
  path: '/admin',
  component: Admin,
  beforeEnter: (to, from, next) => {
    // 验证逻辑
  }
}

3. 组件内守卫

 
export default {
  beforeRouteEnter(to, from, next) {
    // 组件渲染前调用
  },
  beforeRouteUpdate(to, from) {
    // 路由改变但组件复用时
  },
  beforeRouteLeave(to, from) {
    // 导航离开时
  }
}

五、高级特性

1. 路由元信息

 
{
  path: '/dashboard',
  meta: { requiresAuth: true }
}

2. 滚动行为 scrollBehavior

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

3. 路由懒加载

 
const UserView = () => import('../views/UserView.vue')

六、组合式API使用

 
import { useRouter, useRoute } from 'vue-router'

export default {
  setup() {
    const router = useRouter()
    const route = useRoute()

    const navigate = () => {
      router.push({ name: 'Home' })
    }

    return { navigate }
  }
}

七、常见问题解决方案

1. 路由权限控制

 
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isAuthenticated()) {
    next('/login')
  } else {
    next()
  }
})

2. 动态添加路由

 
router.addRoute({
  path: '/new-route',
  component: NewComponent
})
// Vue2中,可以通过路由的addRoutes() 和 addRoute() 两种方法实现路由权限动态渲染

3. 404页面处理

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

// Vue2中
{
  path: '*',
  component: () => import('./components/NotFound.vue') // 导入404组件
}

八、注意事项

  1. paramspath不能同时使用
  2. 路由组件复用时的生命周期问题
  3. Hash模式与History模式的区别
  4. 导航守卫执行顺序:全局 → 路由 → 组件

希望这个文档能帮助您系统复习Vue Router核心知识!🎯建议结合官方文档和实际项目经验进行深入理解。