MST

星途 面试题库

面试题:Vue Router的导航守卫在实际应用中的最佳实践场景及实现方式

请举例说明Vue Router的全局前置守卫、路由独享守卫和组件内守卫在实际业务场景中的应用,比如权限控制、页面访问验证等,并给出相应的代码示例。
20.2万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

全局前置守卫

全局前置守卫会在每次路由切换前被调用,非常适合做权限控制。例如,只有登录用户才能访问某些页面。

import router from './router'
import store from './store'

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

在路由配置中,需要添加 meta 字段来标记需要登录才能访问的页面:

const routes = [
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  }
]

路由独享守卫

路由独享守卫只对特定路由生效。比如,一个支付页面,只有在购物车有商品且用户已登录时才能访问。

const routes = [
  {
    path: '/payment',
    name: 'Payment',
    component: Payment,
    beforeEnter: (to, from, next) => {
      const isLoggedIn = store.getters.isLoggedIn
      const hasItemsInCart = store.getters.hasItemsInCart
      if (isLoggedIn && hasItemsInCart) {
        next()
      } else {
        if (!isLoggedIn) {
          next('/login')
        } else {
          next('/cart')
        }
      }
    }
  }
]

组件内守卫

组件内守卫在组件内部定义,可用于在进入或离开组件时执行逻辑。例如,在编辑页面离开时提示用户保存未保存的更改。

<template>
  <div>
    <input v-model="editedContent" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      editedContent: ''
    }
  },
  beforeRouteLeave(to, from, next) {
    if (this.editedContent && window.confirm('你有未保存的更改,确定离开吗?')) {
      next()
    } else {
      next(false)
    }
  }
}
</script>