前端vue面试题(持续更新中)

本文深入探讨Vue面试中常见的问题,包括vue-router的路由保护机制,Object.defineProperty()数据劫持的局限性,以及Vue组件间的多种通信方式。文章还涉及虚拟DOM的优势,Vue变化侦测原理,以及Vue组件状态管理和优化策略。
摘要由CSDN通过智能技术生成

vue-router中如何保护路由

分析

路由保护在应用开发过程中非常重要,几乎每个应用都要做各种路由权限管理,因此相当考察使用者基本功。

体验

全局守卫:

const router = createRouter({
    ... })
​
router.beforeEach((to, from) => {
   
  // ...
  // 返回 false 以取消导航
  return false
})

路由独享守卫:

const routes = [
  {
   
    path: '/users/:id',
    component: UserDetails,
    beforeEnter: (to, from) => {
   
      // reject the navigation
      return false
    },
  },
]

组件内的守卫:

const UserDetails = {
   
  template: `...`,
  beforeRouteEnter(to, from) {
   
    // 在渲染该组件的对应路由被验证前调用
  },
  beforeRouteUpdate(to, from) {
   
    // 在当前路由改变,但是该组件被复用时调用
  },
  beforeRouteLeave(to, from) {
   
    // 在导航离开渲染该组件的对应路由时调用
  },
}

回答

  • vue-router中保护路由的方法叫做路由守卫,主要用来通过跳转或取消的方式守卫导航。
  • 路由守卫有三个级别:全局路由独享组件级。影响范围由大到小,例如全局的router.beforeEach(),可以注册一个全局前置守卫,每次路由导航都会经过这个守卫,因此在其内部可以加入控制逻辑决定用户是否可以导航到目标路由;在路由注册的时候可以加入单路由独享的守卫,例如beforeEnter,守卫只在进入路由时触发,因此只会影响这个路由,控制更精确;我们还可以为路由组件添加守卫配置,例如beforeRouteEnter,会在渲染该组件的对应路由被验证前调用,控制的范围更精确了。
  • 用户的任何导航行为都会走navigate方法,内部有个guards队列按顺序执行用户注册的守卫钩子函数,如果没有通过验证逻辑则会取消原有的导航。

原理

runGuardQueue(guards)链式的执行用户在各级别注册的守卫钩子函数,通过则继续下一个级别的守卫,不通过进入catch流程取消原本导航

// 源码
runGuardQueue(guards)
  .then(() => {
   
    // check global guards beforeEach
    guards = []
    for (const guard of beforeGuards.list()) {
   
      guards.push(guardToPromiseFn(guard, to, from))
    }
    guards.push(canceledNavigationCheck)

    return runGuardQueue(guards)
  })
  .then(() => {
   
    // check in components beforeRouteUpdate
    guards = extractComponentsGuards(
      updatingRecords,
      'beforeRouteUpdate',
      to,
      from
    )

    for (const record of updatingRecords) {
   
      record.updateGuards.forEach(guard => {
   
        guards.push(guardToPromiseFn(guard, to, from))
      })
    }
    guards.push(canceledNavigationCheck)

    // run the queue of per route beforeEnter guards
    return runGuardQueue(guards)
  })
  .then(() => {
   
    // check the route beforeEnter
    guards = []
    for (const record of to.matched) {
   
      // do not trigger beforeEnter on reused views
      if 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值